use super::into_middleware::{IntoMiddleware, MiddlewareItem};
use super::pending_resource_registrar::PendingResourceRegistration;
use super::route::{HandlerFn, Route};
use super::route_registrar::RouteRegistrar;
use super::router::Router;
use crate::contracts::support::Responsable;
use crate::http::{Controller, Method, Request};
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
pub struct PendingRouteRegistrar<'a> {
router: &'a mut Router,
methods: Vec<Method>,
path: Option<String>,
prefix: Option<String>,
name: Option<String>,
domain: Option<String>,
wheres: HashMap<String, String>,
handler: Option<HandlerFn>,
middleware: Vec<MiddlewareItem>,
excluded_middleware: Vec<String>,
committed: bool,
}
impl<'a> PendingRouteRegistrar<'a> {
pub fn new(router: &'a mut Router) -> Self {
Self {
router,
methods: Vec::new(),
path: None,
prefix: None,
name: None,
domain: None,
wheres: HashMap::new(),
handler: None,
middleware: Vec::new(),
excluded_middleware: Vec::new(),
committed: false,
}
}
fn inherit_from<'b>(&'b mut self) -> PendingRouteRegistrar<'b> {
PendingRouteRegistrar {
router: &mut *self.router,
methods: Vec::new(),
path: None,
prefix: self.prefix.clone(),
name: self.name.clone(),
domain: self.domain.clone(),
wheres: self.wheres.clone(),
handler: None,
middleware: self.middleware.clone(),
excluded_middleware: self.excluded_middleware.clone(),
committed: false,
}
}
pub fn add_route<F, Fut, R>(mut self, method: Method, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
let h: HandlerFn = Arc::new(move |req| {
let fut = handler(req);
Box::pin(async move { fut.await.to_response() })
});
self.methods = vec![method];
self.path = Some(path.to_string());
self.handler = Some(h);
self
}
pub fn get<F, Fut, R>(self, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::GET, path, handler)
}
pub fn post<F, Fut, R>(self, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::POST, path, handler)
}
pub fn put<F, Fut, R>(self, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::PUT, path, handler)
}
pub fn patch<F, Fut, R>(self, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::PATCH, path, handler)
}
pub fn delete<F, Fut, R>(self, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::DELETE, path, handler)
}
pub fn head<F, Fut, R>(self, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::HEAD, path, handler)
}
pub fn options<F, Fut, R>(self, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::OPTIONS, path, handler)
}
pub fn trace<F, Fut, R>(self, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::TRACE, path, handler)
}
pub fn connect<F, Fut, R>(self, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.add_route(Method::CONNECT, path, handler)
}
pub fn any<F, Fut, R>(mut self, path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
let methods = vec![
Method::GET,
Method::HEAD,
Method::POST,
Method::PUT,
Method::PATCH,
Method::DELETE,
Method::OPTIONS,
];
let h: HandlerFn = Arc::new(move |req| {
let fut = handler(req);
Box::pin(async move { fut.await.to_response() })
});
self.methods = methods;
self.path = Some(path.to_string());
self.handler = Some(h);
self
}
pub fn r#match<F, Fut, R>(mut self, methods: &[Method], path: &str, handler: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
let h: HandlerFn = Arc::new(move |req| {
let fut = handler(req);
Box::pin(async move { fut.await.to_response() })
});
self.methods = methods.to_vec();
self.path = Some(path.to_string());
self.handler = Some(h);
self
}
pub fn middleware(mut self, middleware: impl IntoMiddleware) -> Self {
self.middleware.extend(middleware.into_middleware_items());
self
}
pub fn without_middleware(mut self, middleware: impl IntoMiddleware) -> Self {
for item in middleware.into_middleware_items() {
if let MiddlewareItem::Alias(name) = item {
self.excluded_middleware.push(name);
}
}
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
let incoming = name.into();
self.name = Some(match self.name.take() {
Some(existing) => format!("{}{}", existing, incoming),
None => incoming,
});
self
}
pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
let incoming = prefix.into();
self.prefix = Some(match self.prefix.take() {
Some(existing) => {
let existing_clean = existing.trim_matches('/');
let incoming_clean = incoming.trim_matches('/');
if existing_clean.is_empty() {
incoming_clean.to_string()
} else if incoming_clean.is_empty() {
existing_clean.to_string()
} else {
format!("{}/{}", existing_clean, incoming_clean)
}
}
None => incoming,
});
self
}
pub fn domain(mut self, domain: impl Into<String>) -> Self {
self.domain = Some(domain.into());
self
}
pub fn r#where(mut self, param: &str, pattern: &str) -> Self {
self.wheres.insert(param.to_string(), pattern.to_string());
self
}
pub fn where_number(self, param: &str) -> Self {
self.r#where(param, r"^[0-9]+$")
}
pub fn where_alpha(self, param: &str) -> Self {
self.r#where(param, r"^[a-zA-Z]+$")
}
pub fn resource<C: Controller + 'static>(
&mut self,
name: &str,
controller: C,
) -> PendingResourceRegistration<'_> {
<Self as RouteRegistrar>::resource(self, name, controller)
}
pub fn api_resource<C: Controller + 'static>(
&mut self,
name: &str,
controller: C,
) -> PendingResourceRegistration<'_> {
<Self as RouteRegistrar>::api_resource(self, name, controller)
}
pub fn group<F>(mut self, callback: F)
where
F: FnOnce(&mut Self),
{
self.committed = true;
callback(&mut self);
}
pub fn has_middleware_group(&self, name: &str) -> bool {
self.router.has_middleware_group(name)
}
pub fn has_middleware_alias(&self, name: &str) -> bool {
self.router.has_middleware_alias(name)
}
pub fn commit(&mut self) {
if self.committed {
return;
}
self.committed = true;
let Some(ref handler) = self.handler else {
return;
};
let raw_path = self.path.as_deref().unwrap_or("/");
let trimmed_path = raw_path.trim_matches('/');
let final_path = match &self.prefix {
Some(p) => {
let trimmed_prefix = p.trim_matches('/');
if trimmed_prefix.is_empty() {
if trimmed_path.is_empty() {
"/".to_string()
} else {
format!("/{}", trimmed_path)
}
} else if trimmed_path.is_empty() {
format!("/{}", trimmed_prefix)
} else {
format!("/{}/{}", trimmed_prefix, trimmed_path)
}
}
None => {
if trimmed_path.is_empty() {
"/".to_string()
} else {
format!("/{}", trimmed_path)
}
}
};
let final_path = if final_path != "/" {
final_path.trim_end_matches('/').to_string()
} else {
final_path
};
let middleware = self
.router
.compile_route_middlewares(&self.middleware, &self.excluded_middleware);
let route = Route::with_details(
Arc::clone(handler),
middleware,
self.name.clone(),
self.domain.clone(),
self.wheres.clone(),
);
self.router
.insert_route_for_methods(&self.methods, &final_path, route);
}
}
impl<'a> RouteRegistrar for PendingRouteRegistrar<'a> {
fn get<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().get(path, handler)
}
fn post<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().post(path, handler)
}
fn put<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().put(path, handler)
}
fn patch<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().patch(path, handler)
}
fn delete<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().delete(path, handler)
}
fn head<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().head(path, handler)
}
fn options<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().options(path, handler)
}
fn trace<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().trace(path, handler)
}
fn connect<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().connect(path, handler)
}
fn any<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().any(path, handler)
}
fn r#match<F, Fut, R>(
&mut self,
methods: &[Method],
path: &str,
handler: F,
) -> PendingRouteRegistrar<'_>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
R: Responsable,
{
self.inherit_from().r#match(methods, path, handler)
}
fn domain(&mut self, domain: impl Into<String>) -> PendingRouteRegistrar<'_> {
self.inherit_from().domain(domain)
}
fn prefix(&mut self, prefix: impl Into<String>) -> PendingRouteRegistrar<'_> {
self.inherit_from().prefix(prefix)
}
fn name(&mut self, name: impl Into<String>) -> PendingRouteRegistrar<'_> {
self.inherit_from().name(name)
}
fn middleware(&mut self, middleware: impl IntoMiddleware) -> PendingRouteRegistrar<'_> {
self.inherit_from().middleware(middleware)
}
fn without_middleware(&mut self, middleware: impl IntoMiddleware) -> PendingRouteRegistrar<'_> {
self.inherit_from().without_middleware(middleware)
}
fn resource<C: Controller + 'static>(
&mut self,
name: &str,
controller: C,
) -> PendingResourceRegistration<'_> {
PendingResourceRegistration::new(
&mut *self.router,
name,
controller,
self.prefix.clone(),
self.name.clone(),
self.domain.clone(),
self.middleware.clone(),
self.excluded_middleware.clone(),
self.wheres.clone(),
)
}
}
impl<'a> Drop for PendingRouteRegistrar<'a> {
fn drop(&mut self) {
self.commit();
}
}