Files
expenses/server/src/routes/extractors/json.rs
T
2026-10-11 08:45:00 +02:00

43 lines
1.0 KiB
Rust

use axum::extract::{FromRequest, Request};
use axum::response::IntoResponse;
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::routes::extractors::ExtractorError;
pub struct Json<T>(pub T);
impl<T, S> FromRequest<S> for Json<T>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = JsonError;
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(Into::into)
}
}
impl<T> IntoResponse for Json<T>
where
T: Serialize,
{
fn into_response(self) -> axum::response::Response {
axum::Json(self.0).into_response()
}
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct JsonError(#[from] axum::extract::rejection::JsonRejection);
impl IntoResponse for JsonError {
fn into_response(self) -> axum::response::Response {
ExtractorError::Json(self).into_response()
}
}