routes: pastes: Finish implementing fetching of pastes

Signed-off-by: ATechnoHazard <amolele@gmail.com>
This commit is contained in:
sphericalkat committed 2020-06-26 00:53:39 +05:30
1 parent 8e44b02235
commit f16e906ff4
6 files changed
+78 -7

No files matched your search

+24 -2
View File
@@ -5,10 +5,11 @@ use rocket::response::status::Custom;
use rocket_contrib::json::Json;
use serde_json::Value;
use crate::core::paste::{entity::Paste, service::create_paste};
use crate::core::paste::{entity::Paste, service::create_paste, service::fetch_paste};
use crate::core::users::{service::create_or_fetch_user};
use crate::utils::{db, phonetic_key};
use crate::utils::phonetic_key::get_random_id;
use diesel::result::Error;
#[post("/", data = "<paste>")]
fn create(mut paste: Json<Paste>, conn: db::DbConn, mut ck: Cookies) -> Custom<Json<Value>> {
@@ -54,6 +55,27 @@ fn create(mut paste: Json<Paste>, conn: db::DbConn, mut ck: Cookies) -> Custom<J
}
}
#[get("/<id>")]
fn fetch(id: String, conn: db::DbConn) -> Custom<Json<Value>> {
let paste = match fetch_paste(id, &conn) {
Ok(paste) => paste,
Err(err) => {
return match err.downcast_ref::<Error>() {
Some(Error::NotFound) => Custom(Status::NotFound, Json(json!({
"err": err.to_string(),
"msg": "Unable to find a paste with that ID"
}))),
_ => Custom(Status::InternalServerError, Json(json!({
"err": err.to_string(),
"msg": "Something went wrong, try again"
})))
}
}
};
Custom(Status::Found, Json(json!(paste)))
}
pub fn fuel(rocket: Rocket) -> Rocket {
rocket.mount("/api/paste", routes![create])
rocket.mount("/api/paste", routes![create, fetch])
}
+6 -1
View File
@@ -1,6 +1,6 @@
use anyhow::Result;
use diesel::pg::PgConnection;
use diesel::RunQueryDsl;
use diesel::prelude::*;
use crate::schema::pastes;
@@ -11,4 +11,9 @@ pub fn create_paste(paste: &Paste, conn: &PgConnection) -> Result<usize> {
.values(paste)
.execute(conn)?;
Ok(rows)
}
pub fn fetch_paste(id: String, conn: &PgConnection) -> Result<Paste> {
let paste = pastes::table.find(id).get_result::<Paste>(conn)?;
Ok(paste)
}
+6 -1
View File
@@ -4,6 +4,11 @@ use diesel::pg::PgConnection;
use super::entity::Paste;
use super::postgres;
pub fn create_paste(paste: &Paste, conn: &PgConnection) -> Result<usize> {
pub fn create_paste(paste: &mut Paste, conn: &PgConnection) -> Result<usize> {
paste.is_url = validator::validate_url(paste.content.clone());
postgres::create_paste(paste, conn)
}
pub fn fetch_paste(id: String, conn: &PgConnection) -> Result<Paste> {
postgres::fetch_paste(id, conn)
}
+1 -1
View File
@@ -1,6 +1,6 @@
table! {
pastes (id) {
id -> Varchar,
id -> Nullable<Varchar>,
belongs_to -> Nullable<Varchar>,
is_url -> Bool,
content -> Text,