From 3aae8ec6da9c1a1a5dffb4e8cd2ffc2560e5b9f1 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Thu, 15 Sep 2022 16:31:30 +0200 Subject: Add `JsonCreate` trait which is a Json with 201 status --- src/routes/auth.rs | 5 +++-- src/routes/mod.rs | 19 ++++++++++++++++++- src/routes/model.rs | 5 +++-- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/routes/auth.rs b/src/routes/auth.rs index 5c9b293..7cd16ad 100644 --- a/src/routes/auth.rs +++ b/src/routes/auth.rs @@ -3,6 +3,7 @@ use crate::models::{ auth::{AuthBody, Claims, LoginCredentials, SignUpForm}, user::User, }; +use crate::routes::JsonCreate; use axum::{routing::post, Json, Router}; /// Create routes for `/v1/auth/` namespace @@ -27,7 +28,7 @@ async fn make_login(Json(payload): Json) -> Result) -> Result, AppError> { +async fn signup(Json(payload): Json) -> Result, AppError> { if payload.password1 != payload.password2 { return Err(AppError::BadRequest( "The inserted passwords do not match".to_string(), @@ -51,5 +52,5 @@ async fn signup(Json(payload): Json) -> Result, AppEr let claims = Claims::new(user.id); let token = claims.get_token()?; - Ok(Json(AuthBody::new(token))) + Ok(JsonCreate(AuthBody::new(token))) } diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 0de7291..c69f18e 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -3,8 +3,25 @@ pub mod model; pub mod user; use crate::errors::AppError; -use axum::response::IntoResponse; +use axum::{ + http::StatusCode, + response::{IntoResponse, Response}, + Json, +}; +use serde::Serialize; pub async fn page_404() -> impl IntoResponse { AppError::NotFound("Route not found".to_string()) } + +/// Extension of `Json` which returns the CREATED status code +pub struct JsonCreate(pub T); + +impl IntoResponse for JsonCreate +where + T: Serialize, +{ + fn into_response(self) -> Response { + (StatusCode::CREATED, Json(self.0)).into_response() + } +} diff --git a/src/routes/model.rs b/src/routes/model.rs index bc66d25..98e41dc 100644 --- a/src/routes/model.rs +++ b/src/routes/model.rs @@ -5,6 +5,7 @@ use crate::models::{ model::{Model, ModelCreate, ModelUpload, ModelUser}, }; use crate::pagination::Pagination; +use crate::routes::JsonCreate; use axum::{ extract::{ContentLengthLimit, Multipart, Path, Query}, routing::{get, post}, @@ -39,7 +40,7 @@ async fn list_models(pagination: Query) -> Result, claims: Claims, -) -> Result, AppError> { +) -> Result, AppError> { let model = Model::new( payload.name, payload.description, @@ -53,7 +54,7 @@ async fn create_model( let model_new = Model::create(model).await?; - Ok(Json(model_new)) + Ok(JsonCreate(model_new)) } /// Get a model with id = `model_id` -- cgit v1.2.3-71-g8e6c