use crate::action::{ActionContext, ApiResponse};
use crate::error::BaseError;
use crate::router::ModuleRouter;
use std::collections::HashMap;
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) -> Self {
let module_name = router.module_name().to_string();
self.modules.insert(module_name, router);
self
}
pub fn module_names(&self) -> Vec<String> {
self.modules.keys().cloned().collect()
}
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()
}
}