use axum::{handler::Handler, routing, Router};
use capy_core::{AppContext, AppError};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RouteInfo {
pub method: &'static str,
pub path: String,
}
#[derive(Clone)]
pub struct Routes {
router: Router<AppContext>,
inventory: Vec<RouteInfo>,
}
impl Default for Routes {
fn default() -> Self {
Self::new()
}
}
macro_rules! route_method {
($method:ident, $name:literal, $doc:literal) => {
#[doc = $doc]
pub fn $method<H, T>(mut self, path: &str, handler: H) -> Self
where
H: Handler<T, AppContext>,
T: 'static,
{
self.router = self.router.route(path, routing::$method(handler));
self.inventory.push(RouteInfo {
method: $name,
path: path.to_owned(),
});
self
}
};
}
impl Routes {
pub fn new() -> Self {
Self {
router: Router::new().fallback(|| async { AppError::NotFound }),
inventory: Vec::new(),
}
}
route_method!(
get,
"GET",
"Register a GET handler (and Axum's implicit HEAD handler)."
);
route_method!(post, "POST", "Register a POST handler.");
route_method!(put, "PUT", "Register a PUT handler.");
route_method!(patch, "PATCH", "Register a PATCH handler.");
route_method!(delete, "DELETE", "Register a DELETE handler.");
pub fn inventory(&self) -> &[RouteInfo] {
&self.inventory
}
pub fn map_router(
mut self,
map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
) -> Self {
self.router = map(self.router);
self
}
pub fn into_router(self) -> Router<AppContext> {
self.router
.method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
}
}