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 error(self, status: u16) -> Self {
145 self.error_response::<capy_core::ApiErrorResponse>(status)
146 }
147
148 pub fn error_response<T: JsonSchema>(self, status: u16) -> Self {
150 self.describe(|operation| {
151 operation.errors.insert(status, SchemaType::of::<T>());
152 })
153 }
154
155 pub fn tag(self, tag: impl Into<String>) -> Self {
157 self.describe(|operation| {
158 operation.tags.insert(tag.into());
159 })
160 }
161
162 pub fn summary(self, summary: impl Into<String>) -> Self {
164 self.describe(|operation| operation.summary = Some(summary.into()))
165 }
166
167 pub fn description(self, description: impl Into<String>) -> Self {
169 self.describe(|operation| operation.description = Some(description.into()))
170 }
171
172 pub fn api_inventory(&self) -> Vec<ApiRouteInfo> {
174 self.contracts
175 .iter()
176 .map(|(index, operation)| {
177 let route = &self.inventory[*index];
178 ApiRouteInfo {
179 method: route.method,
180 path: route.path.clone(),
181 operation_id: operation.id.clone(),
182 response: operation.response.as_ref().map(|(_, schema)| {
183 schema
184 .as_ref()
185 .map_or_else(|| "NoContent".into(), |s| s.name.clone())
186 }),
187 }
188 })
189 .collect()
190 }
191
192 pub fn inventory(&self) -> &[RouteInfo] {
194 &self.inventory
195 }
196
197 pub fn map_router(
200 mut self,
201 map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
202 ) -> Self {
203 self.router = map(self.router);
204 self
205 }
206
207 pub fn into_router(self) -> Router<AppContext> {
209 self.router
210 .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
211 }
212}