use axum::{
Router,
handler::Handler,
routing::{MethodFilter, on},
};
use super::{
EndpointContract, EndpointContractRegistry, EndpointContractValidationError, EndpointMethod,
};
#[cfg(feature = "http-stack")]
use crate::http::{HttpMiddlewareError, HttpMiddlewareStack};
#[derive(Debug, Clone)]
pub struct EndpointRouter<S = (), P: Copy + 'static = &'static str> {
router: Router<S>,
contracts: Vec<EndpointContract<P>>,
}
impl<S, P> Default for EndpointRouter<S, P>
where
S: Clone + Send + Sync + 'static,
P: Copy + 'static,
{
fn default() -> Self {
Self {
router: Router::new(),
contracts: Vec::new(),
}
}
}
impl<S, P> EndpointRouter<S, P>
where
S: Clone + Send + Sync + 'static,
P: Copy + 'static,
{
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn route<H, T>(
mut self,
contract: EndpointContract<P>,
handler: H,
) -> Result<Self, EndpointContractValidationError>
where
H: Handler<T, S>,
T: 'static,
{
self.contracts().validate_addition(&contract)?;
let filter = match contract.method() {
EndpointMethod::Delete => MethodFilter::DELETE,
EndpointMethod::Get => MethodFilter::GET,
EndpointMethod::Head => MethodFilter::HEAD,
EndpointMethod::Options => MethodFilter::OPTIONS,
EndpointMethod::Patch => MethodFilter::PATCH,
EndpointMethod::Post => MethodFilter::POST,
EndpointMethod::Put => MethodFilter::PUT,
};
self.router = self
.router
.route(contract.path().as_str(), on(filter, handler));
self.contracts.push(contract);
Ok(self)
}
#[must_use]
pub fn contracts(&self) -> EndpointContractRegistry<'_, P> {
EndpointContractRegistry::new(&self.contracts)
}
#[must_use]
pub fn with_api_fallbacks(mut self) -> Self {
self.router = self
.router
.fallback(crate::http::route_not_found)
.method_not_allowed_fallback(crate::http::method_not_allowed);
self
}
pub fn into_parts(self) -> (Router<S>, Vec<EndpointContract<P>>) {
(self.router, self.contracts)
}
#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
pub fn into_router(self, stack: HttpMiddlewareStack) -> Result<Router<S>, HttpMiddlewareError> {
stack.validate_endpoint_contracts(&self.contracts())?;
Ok(stack.apply(self.router))
}
}