use axum::Router;
use crate::error::RoutePathError;
use crate::router::{RouteDefinition, join_paths};
pub struct Controller {
prefix: String,
routes: Vec<RouteDefinition>,
}
impl Controller {
pub fn new(prefix: impl Into<String>) -> Self {
Self {
prefix: prefix.into(),
routes: Vec::new(),
}
}
pub fn try_new(prefix: impl Into<String>) -> Result<Self, RoutePathError> {
let prefix = prefix.into();
join_paths(&prefix, "/").map(|prefix| Self {
prefix,
routes: Vec::new(),
})
}
pub fn route(mut self, route: RouteDefinition) -> Self {
self.routes.push(route);
self
}
pub fn into_router(self) -> Router {
self.try_into_router()
.unwrap_or_else(|error| panic!("{error}"))
}
pub fn try_into_router(self) -> Result<Router, RoutePathError> {
let mut router = Router::new();
for route in self.routes {
let full_path = join_paths(&self.prefix, route.path())?;
router = router.merge(route.into_router(full_path));
}
Ok(router)
}
}