capy-http 0.10.0

Axum routing and JSON response conveniences for Capy.
Documentation
use axum::{
    extract::{FromRequest, FromRequestParts, Request},
    http::request::Parts,
    response::{IntoResponse, Response},
};
use capy_core::AppError;
use serde::{de::DeserializeOwned, Serialize};

/// Deserialize path parameters with safe Capy JSON rejections.
/// Native extraction remains available as `capy::axum::extract::Path`.
#[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())
                }
            })
    }
}

/// Deserialize a query string with safe Capy JSON rejections.
/// Native extraction remains available as `capy::axum::extract::Query`.
#[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()))
    }
}

/// Deserialize or return JSON, using Capy's safe rejection envelope.
/// Put this extractor last because it consumes the body. Native extraction is
/// available as `capy::axum::Json`.
#[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()
    }
}