Return JSON error responses.
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
pub mod json;
|
||||
pub mod path;
|
||||
@@ -0,0 +1,32 @@
|
||||
use axum::extract::{FromRequest, Request};
|
||||
use axum::response::IntoResponse;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
pub struct Json<T>(pub T);
|
||||
|
||||
impl<T, S> FromRequest<S> for Json<T>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = AppError;
|
||||
|
||||
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||
axum::Json::<T>::from_request(request, state)
|
||||
.await
|
||||
.map(|axum::Json(value)| Self(value))
|
||||
.map_err(|rejection| AppError::BadRequest(rejection.body_text()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IntoResponse for Json<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
axum::Json(self.0).into_response()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
use axum::extract::FromRequestParts;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
pub struct Path<T>(pub T);
|
||||
|
||||
impl<T, S> FromRequestParts<S> for Path<T>
|
||||
where
|
||||
T: DeserializeOwned + Send,
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = AppError;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut axum::http::request::Parts,
|
||||
state: &S,
|
||||
) -> Result<Self, Self::Rejection> {
|
||||
axum::extract::Path::<T>::from_request_parts(parts, state)
|
||||
.await
|
||||
.map(|axum::extract::Path(value)| Self(value))
|
||||
.map_err(|rejection| AppError::BadRequest(rejection.body_text()))
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,4 @@
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
};
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -20,6 +16,7 @@ use crate::{
|
||||
dtos::scheduled_transaction::{
|
||||
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData,
|
||||
},
|
||||
extractors::{json::Json, path::Path},
|
||||
validation::scheduled_transaction::ValidatedRecurringTransaction,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
};
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -17,6 +13,7 @@ use crate::{
|
||||
error::AppError,
|
||||
routes::{
|
||||
dtos::transaction::{Transaction, TransactionData},
|
||||
extractors::{json::Json, path::Path},
|
||||
validation::transaction::ValidatedTransaction,
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user