From 50ebffb45987e95e8b2327fb70ec924e2ca3ab4c Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Thu, 17 Aug 2023 10:56:08 +0200 Subject: [PATCH] feat(server): POST request to create distros --- server/src/db/entities/distro.rs | 1 + server/src/db/query/distro.rs | 6 ++++++ server/src/error.rs | 8 +++++--- server/src/web/api/distros.rs | 9 ++++++++- 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/server/src/db/entities/distro.rs b/server/src/db/entities/distro.rs index 1d96872..835cba5 100644 --- a/server/src/db/entities/distro.rs +++ b/server/src/db/entities/distro.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; #[sea_orm(table_name = "distro")] pub struct Model { #[sea_orm(primary_key)] + #[serde(skip_deserializing)] pub id: i32, #[sea_orm(unique)] pub slug: String, diff --git a/server/src/db/query/distro.rs b/server/src/db/query/distro.rs index 2d4d1c6..1913f99 100644 --- a/server/src/db/query/distro.rs +++ b/server/src/db/query/distro.rs @@ -43,4 +43,10 @@ impl DistroQuery { Distro::insert(model).exec(&self.conn).await } + + pub async fn insert_model(&self, model: distro::Model) -> Result { + let mut model: distro::ActiveModel = model.into(); + model.id = NotSet; + model.insert(&self.conn).await + } } diff --git a/server/src/error.rs b/server/src/error.rs index 4fbb7c4..723e944 100644 --- a/server/src/error.rs +++ b/server/src/error.rs @@ -35,10 +35,12 @@ impl IntoResponse for ServerError { ServerError::IO(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), ServerError::Axum(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), ServerError::Status(status) => status.into_response(), - ServerError::Db(sea_orm::DbErr::RecordNotFound(_)) => { - StatusCode::NOT_FOUND.into_response() + ServerError::Db(err) => match err { + sea_orm::DbErr::RecordNotFound(_) => StatusCode::NOT_FOUND, + sea_orm::DbErr::Query(_) => StatusCode::BAD_REQUEST, + _ => StatusCode::INTERNAL_SERVER_ERROR, } - ServerError::Db(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), + .into_response(), } } } diff --git a/server/src/web/api/distros.rs b/server/src/web/api/distros.rs index feb3679..d846398 100644 --- a/server/src/web/api/distros.rs +++ b/server/src/web/api/distros.rs @@ -9,7 +9,7 @@ use crate::db; pub fn router() -> Router { Router::new() - .route("/", get(get_distros)) + .route("/", get(get_distros).post(post_distro)) .route("/:id", get(get_single_distro)) } @@ -41,3 +41,10 @@ async fn get_single_distro( Ok(Json(repo)) } + +async fn post_distro( + State(global): State, + Json(model): Json, +) -> crate::Result> { + Ok(Json(global.db.distro.insert_model(model).await?)) +}