capy-http 0.1.0

Axum routing and JSON response conveniences for Capy.
Documentation
use axum::{handler::Handler, routing, Router};
use capy_core::{AppContext, AppError};

/// 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>,
}

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(),
        }
    }

    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.");

    /// 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 })
    }
}