capy-http 0.8.0

Axum routing and JSON response conveniences for Capy.
Documentation
use crate::contract::{ApiOperation, ApiRouteInfo, SchemaType};
use axum::{handler::Handler, routing, Router};
use capy_core::{AppContext, AppError};
use schemars::JsonSchema;
use std::collections::BTreeMap;

/// A declared route, used by `capy routes` without connecting to a database.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RouteInfo {
    /// HTTP method (GET also accepts HEAD, following Axum).
    pub method: &'static str,
    /// Axum path, with parameters written as `{id}`.
    pub path: String,
}

/// A native Axum router together with a small, explicit route inventory.
#[derive(Clone)]
pub struct Routes {
    router: Router<AppContext>,
    inventory: Vec<RouteInfo>,
    pub(crate) contracts: BTreeMap<usize, ApiOperation>,
    pub(crate) contract_error: Option<String>,
}

impl Default for Routes {
    fn default() -> Self {
        Self::new()
    }
}

macro_rules! route_method {
    ($method:ident, $name:literal, $doc:literal) => {
        #[doc = $doc]
        pub fn $method<H, T>(mut self, path: &str, handler: H) -> Self
        where
            H: Handler<T, AppContext>,
            T: 'static,
        {
            self.router = self.router.route(path, routing::$method(handler));
            self.inventory.push(RouteInfo {
                method: $name,
                path: path.to_owned(),
            });
            self
        }
    };
}

impl Routes {
    /// Start an empty router with JSON 404 and 405 responses.
    pub fn new() -> Self {
        Self {
            router: Router::new().fallback(|| async { AppError::NotFound }),
            inventory: Vec::new(),
            contracts: BTreeMap::new(),
            contract_error: None,
        }
    }

    route_method!(
        get,
        "GET",
        "Register a GET handler (and Axum's implicit HEAD handler)."
    );
    route_method!(post, "POST", "Register a POST handler.");
    route_method!(put, "PUT", "Register a PUT handler.");
    route_method!(patch, "PATCH", "Register a PATCH handler.");
    route_method!(delete, "DELETE", "Register a DELETE handler.");

    fn describe(mut self, change: impl FnOnce(&mut ApiOperation)) -> Self {
        if let Some(index) = self.inventory.len().checked_sub(1) {
            change(self.contracts.entry(index).or_default());
        } else {
            self.contract_error = Some("Contract metadata must follow a route: .get(path, handler).operation(\"name\").response::<ResponseDto>().".into());
        }
        self
    }

    /// Give the preceding route a stable, unique API operation identifier.
    /// Handlers are not introspected; describe their actual JSON wire types explicitly.
    pub fn operation(self, id: impl Into<String>) -> Self {
        self.describe(|operation| operation.id = Some(id.into()))
    }

    /// Describe the preceding route's JSON 200 response using serialization semantics.
    pub fn response<T: JsonSchema>(self) -> Self {
        self.response_status::<T>(200)
    }

    /// Describe the preceding route's JSON 201 response.
    pub fn created<T: JsonSchema>(self) -> Self {
        self.response_status::<T>(201)
    }

    /// Describe another successful JSON status. Use `no_content` for HTTP 204.
    pub fn response_status<T: JsonSchema>(self, status: u16) -> Self {
        self.describe(|operation| operation.response = Some((status, Some(SchemaType::of::<T>()))))
    }

    /// Describe HTTP 204 with no response body.
    pub fn no_content(self) -> Self {
        self.describe(|operation| operation.response = Some((204, None)))
    }

    /// Describe a required `Json<T>` or `Validated<T>` body using deserialization semantics.
    /// Adds the extractor's 400, 413, 415 and 422 error responses.
    pub fn body<T: JsonSchema>(self) -> Self {
        self.describe(|operation| {
            operation.body = Some(SchemaType::of::<T>());
            for status in [400, 413, 415, 422] {
                operation
                    .errors
                    .entry(status)
                    .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
            }
        })
    }

    /// Describe a flat query DTO, including Serde defaults and validation constraints.
    /// Adds the query extractor's 400 error response.
    pub fn query<T: JsonSchema>(self) -> Self {
        self.describe(|operation| {
            operation.query = Some(SchemaType::of::<T>());
            operation
                .errors
                .entry(400)
                .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
        })
    }

    /// Describe one named path parameter's wire type. Repeat for multiple parameters.
    /// Adds the path extractor's 400 error response.
    pub fn path<T: JsonSchema>(self, name: impl Into<String>) -> Self {
        self.describe(|operation| {
            operation.path.insert(name.into(), SchemaType::of::<T>());
            operation
                .errors
                .entry(400)
                .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
        })
    }

    /// Declare session authentication on the preceding operation and add its 401 response.
    /// This is contract metadata; enforce identity with the AuthUser extractor.
    pub fn authenticated(self) -> Self {
        self.describe(|operation| operation.authenticated = true)
            .error(401)
    }

    /// Add a meaningful application error response using Capy's common envelope.
    pub fn error(self, status: u16) -> Self {
        self.error_response::<capy_core::ApiErrorResponse>(status)
    }

    /// Describe a custom JSON error envelope, for example readiness HTTP 503.
    pub fn error_response<T: JsonSchema>(self, status: u16) -> Self {
        self.describe(|operation| {
            operation.errors.insert(status, SchemaType::of::<T>());
        })
    }

    /// Group the preceding operation in API documentation.
    pub fn tag(self, tag: impl Into<String>) -> Self {
        self.describe(|operation| {
            operation.tags.insert(tag.into());
        })
    }

    /// Add a short summary to the preceding operation.
    pub fn summary(self, summary: impl Into<String>) -> Self {
        self.describe(|operation| operation.summary = Some(summary.into()))
    }

    /// Add an optional Markdown description to the preceding operation.
    pub fn description(self, description: impl Into<String>) -> Self {
        self.describe(|operation| operation.description = Some(description.into()))
    }

    /// Return explicitly registered API metadata without opening a database connection.
    pub fn api_inventory(&self) -> Vec<ApiRouteInfo> {
        self.contracts
            .iter()
            .map(|(index, operation)| {
                let route = &self.inventory[*index];
                ApiRouteInfo {
                    method: route.method,
                    path: route.path.clone(),
                    operation_id: operation.id.clone(),
                    response: operation.response.as_ref().map(|(_, schema)| {
                        schema
                            .as_ref()
                            .map_or_else(|| "NoContent".into(), |s| s.name.clone())
                    }),
                }
            })
            .collect()
    }

    /// Return the routes declared through Capy's fluent API.
    pub fn inventory(&self) -> &[RouteInfo] {
        &self.inventory
    }

    /// Access Axum directly for middleware, nesting, and other native features.
    /// Routes added here are not included in Capy's route inventory.
    pub fn map_router(
        mut self,
        map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
    ) -> Self {
        self.router = map(self.router);
        self
    }

    /// Consume this wrapper and return the native Axum router, awaiting state.
    pub fn into_router(self) -> Router<AppContext> {
        self.router
            .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
    }
}