1use axum::{handler::Handler, routing, Router};
2use capy_core::{AppContext, AppError};
3
4#[derive(Clone, Debug, PartialEq, Eq)]
6pub struct RouteInfo {
7 pub method: &'static str,
9 pub path: String,
11}
12
13#[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 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 pub fn inventory(&self) -> &[RouteInfo] {
65 &self.inventory
66 }
67
68 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 pub fn into_router(self) -> Router<AppContext> {
80 self.router
81 .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
82 }
83}