1use axum::{
2 extract::{FromRequest, FromRequestParts, Request},
3 http::request::Parts,
4 response::{IntoResponse, Response},
5};
6use capy_core::AppError;
7use serde::{de::DeserializeOwned, Serialize};
8
9#[derive(Debug, Clone, Copy)]
12pub struct Path<T>(pub T);
13
14impl<S: Send + Sync, T: DeserializeOwned + Send> FromRequestParts<S> for Path<T> {
15 type Rejection = AppError;
16
17 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, AppError> {
18 axum::extract::Path::<T>::from_request_parts(parts, state)
19 .await
20 .map(|value| Self(value.0))
21 .map_err(|error| {
22 if error.status().is_server_error() {
23 AppError::Configuration("Invalid path extractor configuration".into())
24 } else {
25 AppError::BadRequest("Invalid path parameter".into())
26 }
27 })
28 }
29}
30
31#[derive(Debug, Clone, Copy)]
34pub struct Query<T>(pub T);
35
36impl<S: Send + Sync, T: DeserializeOwned> FromRequestParts<S> for Query<T> {
37 type Rejection = AppError;
38
39 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, AppError> {
40 axum::extract::Query::<T>::from_request_parts(parts, state)
41 .await
42 .map(|value| Self(value.0))
43 .map_err(|_| AppError::BadRequest("Invalid query parameters".into()))
44 }
45}
46
47#[derive(Debug, Clone, Copy)]
51pub struct Json<T>(pub T);
52
53impl<S: Send + Sync, T: DeserializeOwned> FromRequest<S> for Json<T> {
54 type Rejection = AppError;
55
56 async fn from_request(request: Request, state: &S) -> Result<Self, AppError> {
57 axum::Json::<T>::from_request(request, state)
58 .await
59 .map(|value| Self(value.0))
60 .map_err(AppError::from_json_rejection)
61 }
62}
63
64impl<T: Serialize> IntoResponse for Json<T> {
65 fn into_response(self) -> Response {
66 axum::Json(self.0).into_response()
67 }
68}