Plume/src/api/posts.rs

84 lines
2.2 KiB
Rust
Raw Normal View History

2018-12-24 16:42:40 +01:00
use canapi::{Error as ApiError, Provider};
2018-09-29 16:45:27 +02:00
use rocket::http::uri::Origin;
use rocket_contrib::json::Json;
2018-12-24 16:42:40 +01:00
use scheduled_thread_pool::ScheduledThreadPool;
2018-09-19 16:49:34 +02:00
use serde_json;
2018-09-29 16:45:27 +02:00
use serde_qs;
2018-09-19 16:49:34 +02:00
2019-03-20 17:56:17 +01:00
use api::authorization::*;
2018-09-25 21:45:32 +02:00
use plume_api::posts::PostEndpoint;
use plume_models::{
2019-03-20 17:56:17 +01:00
db_conn::DbConn, posts::Post, search::Searcher as UnmanagedSearcher, Connection,
};
2018-12-24 16:42:40 +01:00
use {Searcher, Worker};
2018-09-19 16:49:34 +02:00
#[get("/posts/<id>")]
2019-03-20 17:56:17 +01:00
pub fn get(
id: i32,
conn: DbConn,
worker: Worker,
auth: Option<Authorization<Read, Post>>,
search: Searcher,
) -> Json<serde_json::Value> {
let post = <Post as Provider<(
&Connection,
&ScheduledThreadPool,
&UnmanagedSearcher,
Option<i32>,
)>>::get(&(&*conn, &worker, &search, auth.map(|a| a.0.user_id)), id)
.ok();
Json(json!(post))
2018-09-25 21:45:32 +02:00
}
#[get("/posts")]
2019-03-20 17:56:17 +01:00
pub fn list(
conn: DbConn,
uri: &Origin,
worker: Worker,
auth: Option<Authorization<Read, Post>>,
search: Searcher,
) -> Json<serde_json::Value> {
let query: PostEndpoint =
serde_qs::from_str(uri.query().unwrap_or("")).expect("api::list: invalid query error");
let post = <Post as Provider<(
&Connection,
&ScheduledThreadPool,
&UnmanagedSearcher,
Option<i32>,
)>>::list(
&(&*conn, &worker, &search, auth.map(|a| a.0.user_id)),
query,
);
Json(json!(post))
}
2018-12-24 16:42:40 +01:00
#[post("/posts", data = "<payload>")]
2019-03-20 17:56:17 +01:00
pub fn create(
conn: DbConn,
payload: Json<PostEndpoint>,
worker: Worker,
auth: Authorization<Write, Post>,
search: Searcher,
) -> Json<serde_json::Value> {
let new_post = <Post as Provider<(
&Connection,
&ScheduledThreadPool,
&UnmanagedSearcher,
Option<i32>,
)>>::create(
&(&*conn, &worker, &search, Some(auth.0.user_id)),
(*payload).clone(),
);
Json(new_post.map(|p| json!(p)).unwrap_or_else(|e| {
json!({
"error": "Invalid data, couldn't create new post",
"details": match e {
ApiError::Fetch(msg) => msg,
ApiError::SerDe(msg) => msg,
ApiError::NotFound(msg) => msg,
ApiError::Authorization(msg) => msg,
}
})
}))
2018-12-24 16:42:40 +01:00
}