From 7ba652e291bb52d97faa6d21e7821a64664a00ae Mon Sep 17 00:00:00 2001 From: Cara Salter Date: Sun, 29 May 2022 23:47:06 -0400 Subject: handlers: Implement CRD handlers Update handler was removed for now. Also postgres! --- src/handlers/ships.rs | 43 ++++++++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 11 deletions(-) (limited to 'src/handlers') diff --git a/src/handlers/ships.rs b/src/handlers/ships.rs index 5e8c000..ddb81a6 100644 --- a/src/handlers/ships.rs +++ b/src/handlers/ships.rs @@ -1,23 +1,44 @@ -use axum::{Json, extract::Path}; -use solarlib::ship::{Ship, Sha256}; +use std::sync::Arc; -use crate::errors::{JsonResult, StringResult}; +use axum::{Json, extract::Path, Extension}; +use solarlib::ship::{Ship, DbShip, Sha256}; +use sqlx::{query_as, query}; +use crate::{errors::{JsonResult, StringResult}, State}; -pub async fn list() -> JsonResult>> { + +pub async fn list(state: Extension>) -> JsonResult>> { let mut result: Vec = Vec::new(); - Ok(Json(result)) + let mut conn = state.conn.acquire().await?; + + let db_ships = query_as!(DbShip, "SELECT * FROM ships").fetch_all(&mut conn).await?; + + let ships = db_ships.into_iter().map(|d| d.into()).collect::>(); + + Ok(Json(ships)) } -pub async fn new(Json(new_ship): Json) -> StringResult { - unimplemented!(); +pub async fn new(Json(new_ship): Json, state: Extension>) -> StringResult { + let mut conn = state.conn.acquire().await?; + + query!("INSERT INTO ships (name, shasum, download_url, version) VALUES ($1, $2, $3, $4)", new_ship.name, new_ship.shasum.to_string(), new_ship.download_url, new_ship.version).execute(&mut conn).await?; + + Ok("OK") } -pub async fn update(Json(new_ship): Json) -> StringResult { - todo!(); +pub async fn delete(Path(shasum): Path, state: Extension>) -> StringResult { + let mut conn = state.conn.acquire().await?; + + query!("DELETE FROM ships WHERE shasum=$1", shasum.to_string()).execute(&mut conn).await?; + + Ok("OK") } -pub async fn delete(Path(shasum): Path) -> StringResult { - todo!(); +pub async fn get(Path(shasum): Path, state: Extension>) -> JsonResult> { + let mut conn = state.conn.acquire().await?; + + let db_ship = query_as!(DbShip, "SELECT * FROM ships WHERE shasum=$1", shasum.to_string()).fetch_one(&mut conn).await?; + + Ok(Json(db_ship)) } -- cgit v1.2.3