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;
|
2018-12-06 18:54:16 +01:00
|
|
|
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
|
|
|
|
2018-09-25 21:45:32 +02:00
|
|
|
use plume_api::posts::PostEndpoint;
|
2018-09-29 19:14:48 +02:00
|
|
|
use plume_models::{
|
|
|
|
Connection,
|
|
|
|
db_conn::DbConn,
|
|
|
|
posts::Post,
|
2018-12-02 17:37:51 +01:00
|
|
|
search::Searcher as UnmanagedSearcher,
|
2018-09-29 19:14:48 +02:00
|
|
|
};
|
2018-10-23 11:37:24 +02:00
|
|
|
use api::authorization::*;
|
2018-12-24 16:42:40 +01:00
|
|
|
use {Searcher, Worker};
|
2018-09-19 16:49:34 +02:00
|
|
|
|
|
|
|
#[get("/posts/<id>")]
|
2018-12-24 16:42:40 +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();
|
2018-10-23 11:37:24 +02:00
|
|
|
Json(json!(post))
|
2018-09-25 21:45:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[get("/posts")]
|
2018-12-24 16:42:40 +01:00
|
|
|
pub fn list(conn: DbConn, uri: &Origin, worker: Worker, auth: Option<Authorization<Read, Post>>, search: Searcher) -> Json<serde_json::Value> {
|
2018-10-23 11:37:24 +02:00
|
|
|
let query: PostEndpoint = serde_qs::from_str(uri.query().unwrap_or("")).expect("api::list: invalid query error");
|
2018-12-24 16:42:40 +01:00
|
|
|
let post = <Post as Provider<(&Connection, &ScheduledThreadPool, &UnmanagedSearcher, Option<i32>)>>
|
|
|
|
::list(&(&*conn, &worker, &search, auth.map(|a| a.0.user_id)), query);
|
2018-10-23 11:37:24 +02:00
|
|
|
Json(json!(post))
|
|
|
|
}
|
2018-12-24 16:42:40 +01:00
|
|
|
|
|
|
|
#[post("/posts", data = "<payload>")]
|
|
|
|
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,
|
|
|
|
}
|
|
|
|
})))
|
|
|
|
}
|
|
|
|
|