use axum::handler::Handler;
use axum::routing::{delete, get, head, options, patch, post, put};
use axum::Router;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RouteGuard {
pub permission: Option<String>,
pub public: bool,
pub audit: Option<String>,
}
impl RouteGuard {
pub fn permission(permission: impl Into<String>) -> Self {
Self {
permission: Some(permission.into()),
..Default::default()
}
}
pub fn public() -> Self {
Self {
permission: None,
public: true,
audit: None,
}
}
pub fn auditing(action: impl Into<String>) -> Self {
Self {
audit: Some(action.into()),
..Default::default()
}
}
}
#[derive(Debug, Clone)]
pub struct RouteEntry {
pub method: String,
pub path: String,
pub guard: RouteGuard,
}
type RouteBuilder = Box<dyn FnOnce(Router) -> Router + Send>;
pub struct WordvalRouter {
builders: Vec<RouteBuilder>,
routes: Vec<RouteEntry>,
}
impl WordvalRouter {
pub fn new() -> Self {
Self {
builders: Vec::new(),
routes: Vec::new(),
}
}
pub fn list_routes(&self) -> &[RouteEntry] {
&self.routes
}
fn record(&mut self, method: &str, path: &str, guard: RouteGuard) {
self.routes.push(RouteEntry {
method: method.to_string(),
path: path.to_string(),
guard,
});
}
pub fn add_get<H, T>(&mut self, path: &str, handler: H)
where
H: Handler<T, ()>,
T: 'static,
{
self.add_route("GET", path, handler);
}
pub fn add_post<H, T>(&mut self, path: &str, handler: H)
where
H: Handler<T, ()>,
T: 'static,
{
self.add_route("POST", path, handler);
}
pub fn add_put<H, T>(&mut self, path: &str, handler: H)
where
H: Handler<T, ()>,
T: 'static,
{
self.add_route("PUT", path, handler);
}
pub fn add_delete<H, T>(&mut self, path: &str, handler: H)
where
H: Handler<T, ()>,
T: 'static,
{
self.add_route("DELETE", path, handler);
}
pub fn add_route<H, T>(&mut self, method: &str, path: &str, handler: H)
where
H: Handler<T, ()>,
T: 'static,
{
self.add_route_guarded(method, path, handler, RouteGuard::default());
}
pub fn add_route_guarded<H, T>(
&mut self,
method: &str,
path: &str,
handler: H,
guard: RouteGuard,
) where
H: Handler<T, ()>,
T: 'static,
{
self.add_route_impl(
method,
path,
handler,
guard,
None::<fn(axum::routing::MethodRouter<()>) -> axum::routing::MethodRouter<()>>,
);
}
pub fn add_route_with_layer<H, T>(
&mut self,
method: &str,
path: &str,
handler: H,
wrap: impl FnOnce(axum::routing::MethodRouter<()>) -> axum::routing::MethodRouter<()>
+ Send
+ 'static,
) where
H: Handler<T, ()>,
T: 'static,
{
self.add_route_impl(method, path, handler, RouteGuard::default(), Some(wrap));
}
fn add_route_impl<H, T>(
&mut self,
method: &str,
path: &str,
handler: H,
guard: RouteGuard,
wrap: Option<
impl FnOnce(axum::routing::MethodRouter<()>) -> axum::routing::MethodRouter<()>
+ Send
+ 'static,
>,
) where
H: Handler<T, ()>,
T: 'static,
{
let method = method.to_uppercase();
if !matches!(
method.as_str(),
"GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"
) {
tracing::error!("不支持的路由方法 '{}',路由 {} 未注册", method, path);
return;
}
self.record(&method, path, guard);
let path = path.to_string();
self.builders.push(Box::new(move |r| {
let router = match method.as_str() {
"GET" => get(handler),
"POST" => post(handler),
"PUT" => put(handler),
"PATCH" => patch(handler),
"DELETE" => delete(handler),
"HEAD" => head(handler),
"OPTIONS" => options(handler),
_ => return r,
};
let router = match wrap {
Some(w) => w(router),
None => router,
};
r.route(&path, router)
}));
}
pub fn merge(&mut self, prefix: &str, sub: WordvalRouter) {
let prefix = prefix.trim_matches('/');
for r in &sub.routes {
self.record(
&r.method,
&crate::middleware::auth::join_route_path(prefix, &r.path),
r.guard.clone(),
);
}
let nested = format!("/{prefix}");
self.builders
.push(Box::new(move |r| r.nest(&nested, sub.into_axum())));
}
pub fn into_axum(self) -> Router {
self.builders.into_iter().fold(Router::new(), |r, f| f(r))
}
}
impl Default for WordvalRouter {
fn default() -> Self {
Self::new()
}
}