From 6bdf5059f880c090c62b1a43a4f8bc705590d729 Mon Sep 17 00:00:00 2001 From: alok8bb Date: Sun, 30 Jul 2023 22:47:08 +0530 Subject: [PATCH] add fetch paste route Signed-off-by: alok8bb --- src/db.rs | 15 ++++++++++++--- src/main.rs | 23 ++++++++++++++++++++--- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/db.rs b/src/db.rs index 83c32ff..464f57b 100644 --- a/src/db.rs +++ b/src/db.rs @@ -57,9 +57,18 @@ pub async fn paste_id_exists(client: &Client, paste_id: &String) -> Result Result<(), MyError> { - let insert_stmt_ = format!("INSERT INTO bin.pastes(paste_id, content) VALUES($1, $2)"); - let insert_stmt = client.prepare(&insert_stmt_).await.unwrap(); + let stmt_ = format!("INSERT INTO bin.pastes(paste_id, content) VALUES($1, $2)"); + let stmt = client.prepare(&stmt_).await.unwrap(); - client.query(&insert_stmt, &[&endpoint, &content]).await?; + client.query(&stmt, &[&endpoint, &content]).await?; Ok(()) } + +pub async fn get_paste(client: &Client, endpoint: &String) -> Result { + let stmt_ = format!("SELECT content FROM bin.pastes WHERE paste_id = $1"); + let stmt = client.prepare(&stmt_).await.unwrap(); + + let content: String = client.query_one(&stmt, &[&endpoint]).await?.get(0); + + Ok(content) +} diff --git a/src/main.rs b/src/main.rs index a1b732b..c28bef9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,7 @@ mod cfg; mod db; use crate::db::errors::MyError; use actix_web::{ - post, + get, post, web::{self}, App, Error, HttpResponse, HttpServer, }; @@ -22,8 +22,24 @@ fn generate_endpoint(length: u8) -> String { .collect() } +#[get("/paste/{paste_id}")] +async fn fetch_paste( + db_pool: web::Data, + paste_id: web::Path, +) -> Result { + let client: Client = db_pool.get().await.map_err(MyError::PoolError)?; + if !db::paste_id_exists(&client, &paste_id).await? { + return Ok(HttpResponse::NotFound().json(json!({ + "message": "paste with specified id does not exist" + }))); + } + + let content = db::get_paste(&client, &paste_id).await?; + Ok(HttpResponse::Ok().body(content)) +} + #[post("/paste")] -async fn paste(db_pool: web::Data, body: String) -> Result { +async fn new_paste(db_pool: web::Data, body: String) -> Result { let client: Client = db_pool.get().await.map_err(MyError::PoolError)?; let mut endpoint = generate_endpoint(5); @@ -56,7 +72,8 @@ async fn main() -> std::io::Result<()> { let server = HttpServer::new(move || { App::new() .app_data(web::Data::new(pool.clone())) - .service(paste) + .service(new_paste) + .service(fetch_paste) }) .bind(ADDR)? .run();