Skip to main content

capy_http/
routes.rs

1use crate::contract::{ApiOperation, ApiRouteInfo, SchemaType};
2use axum::{handler::Handler, routing, Router};
3use capy_core::{AppContext, AppError};
4use schemars::JsonSchema;
5use std::collections::BTreeMap;
6
7/// A declared route, used by `capy routes` without connecting to a database.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct RouteInfo {
10    /// HTTP method (GET also accepts HEAD, following Axum).
11    pub method: &'static str,
12    /// Axum path, with parameters written as `{id}`.
13    pub path: String,
14}
15
16/// A native Axum router together with a small, explicit route inventory.
17#[derive(Clone)]
18pub struct Routes {
19    router: Router<AppContext>,
20    inventory: Vec<RouteInfo>,
21    pub(crate) contracts: BTreeMap<usize, ApiOperation>,
22    pub(crate) contract_error: Option<String>,
23}
24
25impl Default for Routes {
26    fn default() -> Self {
27        Self::new()
28    }
29}
30
31macro_rules! route_method {
32    ($method:ident, $name:literal, $doc:literal) => {
33        #[doc = $doc]
34        pub fn $method<H, T>(mut self, path: &str, handler: H) -> Self
35        where
36            H: Handler<T, AppContext>,
37            T: 'static,
38        {
39            self.router = self.router.route(path, routing::$method(handler));
40            self.inventory.push(RouteInfo {
41                method: $name,
42                path: path.to_owned(),
43            });
44            self
45        }
46    };
47}
48
49impl Routes {
50    /// Start an empty router with JSON 404 and 405 responses.
51    pub fn new() -> Self {
52        Self {
53            router: Router::new().fallback(|| async { AppError::NotFound }),
54            inventory: Vec::new(),
55            contracts: BTreeMap::new(),
56            contract_error: None,
57        }
58    }
59
60    route_method!(
61        get,
62        "GET",
63        "Register a GET handler (and Axum's implicit HEAD handler)."
64    );
65    route_method!(post, "POST", "Register a POST handler.");
66    route_method!(put, "PUT", "Register a PUT handler.");
67    route_method!(patch, "PATCH", "Register a PATCH handler.");
68    route_method!(delete, "DELETE", "Register a DELETE handler.");
69
70    fn describe(mut self, change: impl FnOnce(&mut ApiOperation)) -> Self {
71        if let Some(index) = self.inventory.len().checked_sub(1) {
72            change(self.contracts.entry(index).or_default());
73        } else {
74            self.contract_error = Some("Contract metadata must follow a route: .get(path, handler).operation(\"name\").response::<ResponseDto>().".into());
75        }
76        self
77    }
78
79    /// Give the preceding route a stable, unique API operation identifier.
80    /// Handlers are not introspected; describe their actual JSON wire types explicitly.
81    pub fn operation(self, id: impl Into<String>) -> Self {
82        self.describe(|operation| operation.id = Some(id.into()))
83    }
84
85    /// Describe the preceding route's JSON 200 response using serialization semantics.
86    pub fn response<T: JsonSchema>(self) -> Self {
87        self.response_status::<T>(200)
88    }
89
90    /// Describe the preceding route's JSON 201 response.
91    pub fn created<T: JsonSchema>(self) -> Self {
92        self.response_status::<T>(201)
93    }
94
95    /// Describe another successful JSON status. Use `no_content` for HTTP 204.
96    pub fn response_status<T: JsonSchema>(self, status: u16) -> Self {
97        self.describe(|operation| operation.response = Some((status, Some(SchemaType::of::<T>()))))
98    }
99
100    /// Describe HTTP 204 with no response body.
101    pub fn no_content(self) -> Self {
102        self.describe(|operation| operation.response = Some((204, None)))
103    }
104
105    /// Describe a required `Json<T>` or `Validated<T>` body using deserialization semantics.
106    /// Adds the extractor's 400, 413, 415 and 422 error responses.
107    pub fn body<T: JsonSchema>(self) -> Self {
108        self.describe(|operation| {
109            operation.body = Some(SchemaType::of::<T>());
110            for status in [400, 413, 415, 422] {
111                operation
112                    .errors
113                    .entry(status)
114                    .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
115            }
116        })
117    }
118
119    /// Describe a flat query DTO, including Serde defaults and validation constraints.
120    /// Adds the query extractor's 400 error response.
121    pub fn query<T: JsonSchema>(self) -> Self {
122        self.describe(|operation| {
123            operation.query = Some(SchemaType::of::<T>());
124            operation
125                .errors
126                .entry(400)
127                .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
128        })
129    }
130
131    /// Describe one named path parameter's wire type. Repeat for multiple parameters.
132    /// Adds the path extractor's 400 error response.
133    pub fn path<T: JsonSchema>(self, name: impl Into<String>) -> Self {
134        self.describe(|operation| {
135            operation.path.insert(name.into(), SchemaType::of::<T>());
136            operation
137                .errors
138                .entry(400)
139                .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
140        })
141    }
142
143    /// Declare session authentication on the preceding operation and add its 401 response.
144    /// This is contract metadata; enforce identity with the AuthUser extractor.
145    pub fn authenticated(self) -> Self {
146        self.describe(|operation| operation.authenticated = true)
147            .error(401)
148    }
149
150    /// Add a meaningful application error response using Capy's common envelope.
151    pub fn error(self, status: u16) -> Self {
152        self.error_response::<capy_core::ApiErrorResponse>(status)
153    }
154
155    /// Describe a custom JSON error envelope, for example readiness HTTP 503.
156    pub fn error_response<T: JsonSchema>(self, status: u16) -> Self {
157        self.describe(|operation| {
158            operation.errors.insert(status, SchemaType::of::<T>());
159        })
160    }
161
162    /// Group the preceding operation in API documentation.
163    pub fn tag(self, tag: impl Into<String>) -> Self {
164        self.describe(|operation| {
165            operation.tags.insert(tag.into());
166        })
167    }
168
169    /// Add a short summary to the preceding operation.
170    pub fn summary(self, summary: impl Into<String>) -> Self {
171        self.describe(|operation| operation.summary = Some(summary.into()))
172    }
173
174    /// Add an optional Markdown description to the preceding operation.
175    pub fn description(self, description: impl Into<String>) -> Self {
176        self.describe(|operation| operation.description = Some(description.into()))
177    }
178
179    /// Return explicitly registered API metadata without opening a database connection.
180    pub fn api_inventory(&self) -> Vec<ApiRouteInfo> {
181        self.contracts
182            .iter()
183            .map(|(index, operation)| {
184                let route = &self.inventory[*index];
185                ApiRouteInfo {
186                    method: route.method,
187                    path: route.path.clone(),
188                    operation_id: operation.id.clone(),
189                    response: operation.response.as_ref().map(|(_, schema)| {
190                        schema
191                            .as_ref()
192                            .map_or_else(|| "NoContent".into(), |s| s.name.clone())
193                    }),
194                }
195            })
196            .collect()
197    }
198
199    /// Return the routes declared through Capy's fluent API.
200    pub fn inventory(&self) -> &[RouteInfo] {
201        &self.inventory
202    }
203
204    /// Access Axum directly for middleware, nesting, and other native features.
205    /// Routes added here are not included in Capy's route inventory.
206    pub fn map_router(
207        mut self,
208        map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
209    ) -> Self {
210        self.router = map(self.router);
211        self
212    }
213
214    /// Consume this wrapper and return the native Axum router, awaiting state.
215    pub fn into_router(self) -> Router<AppContext> {
216        self.router
217            .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
218    }
219}