use crate::action::{ActionContext, ApiResponse};
use crate::error::BaseError;
use crate::router::ModuleRouter;
use crate::router::{ApiCatalog, ModuleDescriptor};
use std::collections::{HashMap, HashSet};
pub struct AppRouter {
modules: HashMap<String, ModuleRouter>,
}
impl AppRouter {
pub fn new() -> Self {
Self {
modules: HashMap::new(),
}
}
pub fn register_module(mut self, router: ModuleRouter) -> Result<Self, BaseError> {
let module_name = router.module_name().to_string();
if module_name.trim().is_empty() {
return Err(BaseError::ConfigError("模块名称不能为空".to_string()));
}
if self.modules.contains_key(&module_name) {
return Err(BaseError::ConfigError(format!(
"模块已注册: {}",
module_name
)));
}
self.modules.insert(module_name, router);
Ok(self)
}
pub fn module_names(&self) -> Vec<String> {
let mut names: Vec<String> = self.modules.keys().cloned().collect();
names.sort();
names
}
pub fn catalog(&self) -> Result<ApiCatalog, BaseError> {
let mut names: Vec<&String> = self.modules.keys().collect();
names.sort();
let mut modules: Vec<ModuleDescriptor> = Vec::with_capacity(names.len());
let mut routes = HashSet::new();
let mut operations = HashSet::new();
for name in names {
let descriptor = self.modules[name].descriptor()?;
for action in &descriptor.actions {
let route_key = (action.route.method.clone(), action.route.path.clone());
if !routes.insert(route_key) {
return Err(BaseError::ConfigError(format!(
"route 冲突: {} {}",
action.route.method, action.route.path
)));
}
if !operations.insert(action.route.operation_id.clone()) {
return Err(BaseError::ConfigError(format!(
"operation_id 冲突: {}",
action.route.operation_id
)));
}
}
modules.push(descriptor);
}
Ok(ApiCatalog { modules })
}
pub async fn dispatch(
&self,
module_name: &str,
action_name: &str,
context: ActionContext,
) -> Result<ApiResponse, BaseError> {
let module_router = self
.modules
.get(module_name)
.ok_or_else(|| BaseError::ActionNotFound(format!("模块不存在: {}", module_name)))?;
module_router.dispatch(action_name, context).await
}
}
impl Default for AppRouter {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_register_module_rejects_duplicate_module_name() {
let router = AppRouter::new()
.register_module(ModuleRouter::new("user", "用户管理"))
.expect("首次注册 user 模块应成功");
let result = router.register_module(ModuleRouter::new("user", "重复用户模块"));
assert!(matches!(
result,
Err(BaseError::ConfigError(msg)) if msg.contains("模块已注册: user")
));
}
#[test]
fn test_register_module_rejects_blank_module_name() {
let result = AppRouter::new().register_module(ModuleRouter::new(" ", "空白模块"));
assert!(matches!(
result,
Err(BaseError::ConfigError(msg)) if msg.contains("模块名称不能为空")
));
}
}