Skip to main content

capy_http/
routes.rs

1use axum::{handler::Handler, routing, Router};
2use capy_core::{AppContext, AppError};
3
4/// A declared route, used by `capy routes` without connecting to a database.
5#[derive(Clone, Debug, PartialEq, Eq)]
6pub struct RouteInfo {
7    /// HTTP method (GET also accepts HEAD, following Axum).
8    pub method: &'static str,
9    /// Axum path, with parameters written as `{id}`.
10    pub path: String,
11}
12
13/// A native Axum router together with a small, explicit route inventory.
14#[derive(Clone)]
15pub struct Routes {
16    router: Router<AppContext>,
17    inventory: Vec<RouteInfo>,
18}
19
20impl Default for Routes {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26macro_rules! route_method {
27    ($method:ident, $name:literal, $doc:literal) => {
28        #[doc = $doc]
29        pub fn $method<H, T>(mut self, path: &str, handler: H) -> Self
30        where
31            H: Handler<T, AppContext>,
32            T: 'static,
33        {
34            self.router = self.router.route(path, routing::$method(handler));
35            self.inventory.push(RouteInfo {
36                method: $name,
37                path: path.to_owned(),
38            });
39            self
40        }
41    };
42}
43
44impl Routes {
45    /// Start an empty router with JSON 404 and 405 responses.
46    pub fn new() -> Self {
47        Self {
48            router: Router::new().fallback(|| async { AppError::NotFound }),
49            inventory: Vec::new(),
50        }
51    }
52
53    route_method!(
54        get,
55        "GET",
56        "Register a GET handler (and Axum's implicit HEAD handler)."
57    );
58    route_method!(post, "POST", "Register a POST handler.");
59    route_method!(put, "PUT", "Register a PUT handler.");
60    route_method!(patch, "PATCH", "Register a PATCH handler.");
61    route_method!(delete, "DELETE", "Register a DELETE handler.");
62
63    /// Return the routes declared through Capy's fluent API.
64    pub fn inventory(&self) -> &[RouteInfo] {
65        &self.inventory
66    }
67
68    /// Access Axum directly for middleware, nesting, and other native features.
69    /// Routes added here are not included in Capy's route inventory.
70    pub fn map_router(
71        mut self,
72        map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
73    ) -> Self {
74        self.router = map(self.router);
75        self
76    }
77
78    /// Consume this wrapper and return the native Axum router, awaiting state.
79    pub fn into_router(self) -> Router<AppContext> {
80        self.router
81            .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
82    }
83}