use axum::{
Router,
handler::Handler,
routing::{MethodFilter, on},
};
use super::{
EndpointContract, EndpointContractRegistry, EndpointContractValidationError, EndpointMethod,
};
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)?;
self.contracts.push(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));
Ok(self)
}
#[must_use]
pub fn contracts(&self) -> EndpointContractRegistry<'_, P> {
EndpointContractRegistry::new(&self.contracts)
}
pub fn into_router(self, stack: HttpMiddlewareStack) -> Result<Router<S>, HttpMiddlewareError> {
stack.validate_endpoint_contracts(&self.contracts())?;
Ok(stack.apply(self.router))
}
}