mirror of
https://github.com/okiba-org/backend.git
synced 2025-07-25 16:20:27 +00:00
15
src/db.rs
15
src/db.rs
@ -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> {
|
||||
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<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)
|
||||
}
|
||||
|
23
src/main.rs
23
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<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")]
|
||||
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 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();
|
||||
|
Reference in New Issue
Block a user