use axum::extract::rejection::{JsonRejection, QueryRejection};
use axum::extract::{FromRequest, FromRequestParts, Request};
use axum::http::StatusCode;
use axum::http::request::Parts;
use axum::response::{IntoResponse, Response};
use talea_core::api::ApiError;
use crate::http::error::ApiFailure;
pub struct Json<T>(pub T);
impl<S, T> FromRequest<S> for Json<T>
where
axum::Json<T>: FromRequest<S, Rejection = JsonRejection>,
S: Send + Sync,
{
type Rejection = Response;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
match axum::Json::<T>::from_request(req, state).await {
Ok(axum::Json(value)) => Ok(Json(value)),
Err(rejection) => Err(json_rejection_response(rejection)),
}
}
}
impl<T: serde::Serialize> IntoResponse for Json<T> {
fn into_response(self) -> Response {
axum::Json(self.0).into_response()
}
}
fn json_rejection_response(rejection: JsonRejection) -> Response {
match rejection {
JsonRejection::MissingJsonContentType(_) => (
StatusCode::UNSUPPORTED_MEDIA_TYPE,
axum::Json(ApiError::InvalidDraft {
field: "body".into(),
reason: "expected content-type: application/json".into(),
}),
)
.into_response(),
other => ApiFailure(ApiError::InvalidDraft {
field: "body".into(),
reason: other.body_text(),
})
.into_response(),
}
}
pub struct Query<T>(pub T);
impl<S, T> FromRequestParts<S> for Query<T>
where
axum::extract::Query<T>: FromRequestParts<S, Rejection = QueryRejection>,
S: Send + Sync,
{
type Rejection = ApiFailure;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
match axum::extract::Query::<T>::from_request_parts(parts, state).await {
Ok(axum::extract::Query(value)) => Ok(Query(value)),
Err(rejection) => Err(ApiFailure(ApiError::InvalidDraft {
field: "query".into(),
reason: rejection.body_text(),
})),
}
}
}