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#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct RouteInfo {
10 pub method: &'static str,
12 pub path: String,
14}
15
16#[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 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 pub fn operation(self, id: impl Into<String>) -> Self {
82 self.describe(|operation| operation.id = Some(id.into()))
83 }
84
85 pub fn response<T: JsonSchema>(self) -> Self {
87 self.response_status::<T>(200)
88 }
89
90 pub fn created<T: JsonSchema>(self) -> Self {
92 self.response_status::<T>(201)
93 }
94
95 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 pub fn no_content(self) -> Self {
102 self.describe(|operation| operation.response = Some((204, None)))
103 }
104
105 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 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 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 pub fn authenticated(self) -> Self {
146 self.describe(|operation| operation.authenticated = true)
147 .error(401)
148 }
149
150 pub fn error(self, status: u16) -> Self {
152 self.error_response::<capy_core::ApiErrorResponse>(status)
153 }
154
155 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 pub fn tag(self, tag: impl Into<String>) -> Self {
164 self.describe(|operation| {
165 operation.tags.insert(tag.into());
166 })
167 }
168
169 pub fn summary(self, summary: impl Into<String>) -> Self {
171 self.describe(|operation| operation.summary = Some(summary.into()))
172 }
173
174 pub fn description(self, description: impl Into<String>) -> Self {
176 self.describe(|operation| operation.description = Some(description.into()))
177 }
178
179 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 pub fn inventory(&self) -> &[RouteInfo] {
201 &self.inventory
202 }
203
204 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 pub fn into_router(self) -> Router<AppContext> {
216 self.router
217 .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
218 }
219}