use axum::{
extract::{FromRequest, FromRequestParts, Request},
http::request::Parts,
response::{IntoResponse, Response},
};
use capy_core::AppError;
use serde::{de::DeserializeOwned, Serialize};
#[derive(Debug, Clone, Copy)]
pub struct Path<T>(pub T);
impl<S: Send + Sync, T: DeserializeOwned + Send> FromRequestParts<S> for Path<T> {
type Rejection = AppError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, AppError> {
axum::extract::Path::<T>::from_request_parts(parts, state)
.await
.map(|value| Self(value.0))
.map_err(|error| {
if error.status().is_server_error() {
AppError::Configuration("Invalid path extractor configuration".into())
} else {
AppError::BadRequest("Invalid path parameter".into())
}
})
}
}
#[derive(Debug, Clone, Copy)]
pub struct Query<T>(pub T);
impl<S: Send + Sync, T: DeserializeOwned> FromRequestParts<S> for Query<T> {
type Rejection = AppError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, AppError> {
axum::extract::Query::<T>::from_request_parts(parts, state)
.await
.map(|value| Self(value.0))
.map_err(|_| AppError::BadRequest("Invalid query parameters".into()))
}
}
#[derive(Debug, Clone, Copy)]
pub struct Json<T>(pub T);
impl<S: Send + Sync, T: DeserializeOwned> FromRequest<S> for Json<T> {
type Rejection = AppError;
async fn from_request(request: Request, state: &S) -> Result<Self, AppError> {
axum::Json::<T>::from_request(request, state)
.await
.map(|value| Self(value.0))
.map_err(AppError::from_json_rejection)
}
}
impl<T: Serialize> IntoResponse for Json<T> {
fn into_response(self) -> Response {
axum::Json(self.0).into_response()
}
}