add fetch paste route

Signed-off-by: alok8bb <alok8bb@gmail.com>
This commit is contained in:
2023-07-30 22:47:08 +05:30
parent 0923b46377
commit 6bdf5059f8
2 changed files with 32 additions and 6 deletions

View File

@ -57,9 +57,18 @@ pub async fn paste_id_exists(client: &Client, paste_id: &String) -> Result<bool,
} }
pub async fn add_paste(client: &Client, endpoint: &String, content: String) -> Result<(), MyError> { pub async fn add_paste(client: &Client, endpoint: &String, content: String) -> Result<(), MyError> {
let insert_stmt_ = format!("INSERT INTO bin.pastes(paste_id, content) VALUES($1, $2)"); let stmt_ = format!("INSERT INTO bin.pastes(paste_id, content) VALUES($1, $2)");
let insert_stmt = client.prepare(&insert_stmt_).await.unwrap(); let stmt = client.prepare(&stmt_).await.unwrap();
client.query(&insert_stmt, &[&endpoint, &content]).await?; client.query(&stmt, &[&endpoint, &content]).await?;
Ok(()) Ok(())
} }
pub async fn get_paste(client: &Client, endpoint: &String) -> Result<String, MyError> {
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)
}

View File

@ -2,7 +2,7 @@ mod cfg;
mod db; mod db;
use crate::db::errors::MyError; use crate::db::errors::MyError;
use actix_web::{ use actix_web::{
post, get, post,
web::{self}, web::{self},
App, Error, HttpResponse, HttpServer, App, Error, HttpResponse, HttpServer,
}; };
@ -22,8 +22,24 @@ fn generate_endpoint(length: u8) -> String {
.collect() .collect()
} }
#[get("/paste/{paste_id}")]
async fn fetch_paste(
db_pool: web::Data<Pool>,
paste_id: web::Path<String>,
) -> Result<HttpResponse, Error> {
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")] #[post("/paste")]
async fn paste(db_pool: web::Data<Pool>, body: String) -> Result<HttpResponse, Error> { async fn new_paste(db_pool: web::Data<Pool>, body: String) -> Result<HttpResponse, Error> {
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?; let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
let mut endpoint = generate_endpoint(5); let mut endpoint = generate_endpoint(5);
@ -56,7 +72,8 @@ async fn main() -> std::io::Result<()> {
let server = HttpServer::new(move || { let server = HttpServer::new(move || {
App::new() App::new()
.app_data(web::Data::new(pool.clone())) .app_data(web::Data::new(pool.clone()))
.service(paste) .service(new_paste)
.service(fetch_paste)
}) })
.bind(ADDR)? .bind(ADDR)?
.run(); .run();