use axum::{ extract::{ Request, rejection::{ExtensionRejection, JsonRejection, PathRejection}, {FromRequest, FromRequestParts}, }, response::IntoResponse, }; use axum_extra::extract::QueryRejection; use http::request::Parts; use serde::Serialize; use crate::{error_response::ApiError, errors::ApiBadRequest}; pub struct ExtractorError(ApiError); impl IntoResponse for ExtractorError { fn into_response(self) -> axum::response::Response { let mut res = self.0.into_response(); res.extensions_mut().insert(FailedExtraction); res } } #[derive(Clone, Copy)] pub struct FailedExtraction; pub struct Json(pub T); impl FromRequest for Json where axum::extract::Json: FromRequest, S: Send + Sync, { type Rejection = ExtractorError; async fn from_request(req: Request, state: &S) -> Result { axum::extract::Json::::from_request(req, state) .await .map(|json| Json(json.0)) .map_err(|err| { ExtractorError( ApiBadRequest { reason: err.body_text(), } .build() .into(), ) }) } } impl IntoResponse for Json { fn into_response(self) -> axum::response::Response { let Self(value) = self; axum::extract::Json(value).into_response() } } pub struct Query(pub T); impl FromRequestParts for Query where axum_extra::extract::Query: FromRequestParts, S: Send + Sync, { type Rejection = ExtractorError; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { let res = axum_extra::extract::Query::::from_request_parts(parts, state) .await .map(|query| Query(query.0)) .map_err(|err| { ExtractorError( ApiBadRequest { reason: err.body_text(), } .build() .into(), ) }); res } } pub struct Extension(pub T); impl FromRequestParts for Extension where axum::extract::Extension: FromRequestParts, S: Send + Sync, { type Rejection = ExtractorError; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { axum::extract::Extension::::from_request_parts(parts, state) .await .map(|ext| Extension(ext.0)) .map_err(|err| { ExtractorError( ApiBadRequest { reason: err.body_text(), } .build() .into(), ) }) } } pub struct Path(pub T); impl FromRequestParts for Path where axum::extract::Path: FromRequestParts, S: Send + Sync, { type Rejection = ExtractorError; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { axum::extract::Path::::from_request_parts(parts, state) .await .map(|ext| Path(ext.0)) .map_err(|err| { ExtractorError( ApiBadRequest { reason: err.body_text(), } .build() .into(), ) }) } }