use crate::routing::{PendingRouteRegistrar, Router};
pub(crate) type RouterCallback = Box<dyn FnOnce(&mut Router) + 'static>;
pub(crate) type PendingRouteCallback = Box<dyn FnOnce(&mut PendingRouteRegistrar) + 'static>;
#[derive(Default)]
pub struct Routing {
using: Vec<RouterCallback>,
web: Vec<RouterCallback>,
api: Vec<PendingRouteCallback>,
commands: Vec<RouterCallback>,
channels: Vec<RouterCallback>,
health: Option<String>,
api_prefix: String,
then: Vec<RouterCallback>,
}
impl Routing {
pub fn new() -> Self {
Self {
using: Vec::new(),
web: Vec::new(),
api: Vec::new(),
commands: Vec::new(),
channels: Vec::new(),
health: None,
api_prefix: "api".to_string(),
then: Vec::new(),
}
}
pub fn using<F>(&mut self, callback: F) -> &mut Self
where
F: FnOnce(&mut Router) + 'static,
{
self.using.push(Box::new(callback));
self
}
pub fn web<F>(&mut self, callback: F) -> &mut Self
where
F: FnOnce(&mut Router) + 'static,
{
self.web.push(Box::new(callback));
self
}
pub fn api<F>(&mut self, callback: F) -> &mut Self
where
F: FnOnce(&mut PendingRouteRegistrar) + 'static,
{
self.api.push(Box::new(callback));
self
}
pub fn commands<F>(&mut self, callback: F) -> &mut Self
where
F: FnOnce(&mut Router) + 'static,
{
self.commands.push(Box::new(callback));
self
}
pub fn channels<F>(&mut self, callback: F) -> &mut Self
where
F: FnOnce(&mut Router) + 'static,
{
self.channels.push(Box::new(callback));
self
}
pub fn health(&mut self, path: impl Into<String>) -> &mut Self {
self.health = Some(path.into());
self
}
pub fn api_prefix(&mut self, prefix: impl Into<String>) -> &mut Self {
self.api_prefix = prefix.into();
self
}
pub fn then<F>(&mut self, callback: F) -> &mut Self
where
F: FnOnce(&mut Router) + 'static,
{
self.then.push(Box::new(callback));
self
}
pub(crate) fn register(mut self, router: &mut Router) {
if !self.using.is_empty() {
for using in self.using.drain(..) {
using(router);
}
return;
}
if let Some(health_path) = self.health {
let path = health_path.trim();
if !path.is_empty() {
let formatted = if path.starts_with('/') {
path.to_string()
} else {
format!("/{}", path)
};
router.get(&formatted, |_req| async { "OK" });
}
}
for web in self.web.drain(..) {
web(router);
}
if !self.api.is_empty() {
let prefix = self.api_prefix.trim_matches('/').to_string();
let mut pending = router.prefix(prefix);
if pending.has_middleware_group("api") {
pending = pending.middleware("api");
}
let api_callbacks = std::mem::take(&mut self.api);
pending.group(|r| {
for api in api_callbacks {
api(r);
}
});
}
for commands in self.commands.drain(..) {
commands(router);
}
for channels in self.channels.drain(..) {
channels(router);
}
for then in self.then.drain(..) {
then(router);
}
}
}