use crate::contract::{ApiOperation, ApiRouteInfo, SchemaType};
use axum::{handler::Handler, routing, Router};
use capy_core::{AppContext, AppError};
use schemars::JsonSchema;
use std::collections::BTreeMap;
#[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>,
pub(crate) contracts: BTreeMap<usize, ApiOperation>,
pub(crate) contract_error: Option<String>,
}
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(),
contracts: BTreeMap::new(),
contract_error: None,
}
}
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.");
fn describe(mut self, change: impl FnOnce(&mut ApiOperation)) -> Self {
if let Some(index) = self.inventory.len().checked_sub(1) {
change(self.contracts.entry(index).or_default());
} else {
self.contract_error = Some("Contract metadata must follow a route: .get(path, handler).operation(\"name\").response::<ResponseDto>().".into());
}
self
}
pub fn operation(self, id: impl Into<String>) -> Self {
self.describe(|operation| operation.id = Some(id.into()))
}
pub fn response<T: JsonSchema>(self) -> Self {
self.response_status::<T>(200)
}
pub fn created<T: JsonSchema>(self) -> Self {
self.response_status::<T>(201)
}
pub fn response_status<T: JsonSchema>(self, status: u16) -> Self {
self.describe(|operation| operation.response = Some((status, Some(SchemaType::of::<T>()))))
}
pub fn no_content(self) -> Self {
self.describe(|operation| operation.response = Some((204, None)))
}
pub fn body<T: JsonSchema>(self) -> Self {
self.describe(|operation| {
operation.body = Some(SchemaType::of::<T>());
for status in [400, 413, 415, 422] {
operation
.errors
.entry(status)
.or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
}
})
}
pub fn query<T: JsonSchema>(self) -> Self {
self.describe(|operation| {
operation.query = Some(SchemaType::of::<T>());
operation
.errors
.entry(400)
.or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
})
}
pub fn path<T: JsonSchema>(self, name: impl Into<String>) -> Self {
self.describe(|operation| {
operation.path.insert(name.into(), SchemaType::of::<T>());
operation
.errors
.entry(400)
.or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
})
}
pub fn authenticated(self) -> Self {
self.describe(|operation| operation.authenticated = true)
.error(401)
}
pub fn error(self, status: u16) -> Self {
self.error_response::<capy_core::ApiErrorResponse>(status)
}
pub fn error_response<T: JsonSchema>(self, status: u16) -> Self {
self.describe(|operation| {
operation.errors.insert(status, SchemaType::of::<T>());
})
}
pub fn tag(self, tag: impl Into<String>) -> Self {
self.describe(|operation| {
operation.tags.insert(tag.into());
})
}
pub fn summary(self, summary: impl Into<String>) -> Self {
self.describe(|operation| operation.summary = Some(summary.into()))
}
pub fn description(self, description: impl Into<String>) -> Self {
self.describe(|operation| operation.description = Some(description.into()))
}
pub fn api_inventory(&self) -> Vec<ApiRouteInfo> {
self.contracts
.iter()
.map(|(index, operation)| {
let route = &self.inventory[*index];
ApiRouteInfo {
method: route.method,
path: route.path.clone(),
operation_id: operation.id.clone(),
response: operation.response.as_ref().map(|(_, schema)| {
schema
.as_ref()
.map_or_else(|| "NoContent".into(), |s| s.name.clone())
}),
}
})
.collect()
}
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 })
}
}