1use axum::Router;
4
5use crate::error::RoutePathError;
6use crate::router::{RouteDefinition, join_normalized_paths, normalize_mount_prefix};
7
8pub struct Controller {
10 prefix: String,
11 routes: Vec<RouteDefinition>,
12}
13
14impl Controller {
15 pub fn new(prefix: impl Into<String>) -> Self {
17 Self {
18 prefix: prefix.into(),
19 routes: Vec::new(),
20 }
21 }
22
23 pub fn try_new(prefix: impl Into<String>) -> Result<Self, RoutePathError> {
25 normalize_mount_prefix(prefix.into()).map(|prefix| Self {
26 prefix,
27 routes: Vec::new(),
28 })
29 }
30
31 pub fn route(mut self, route: RouteDefinition) -> Self {
33 self.routes.push(route);
34 self
35 }
36
37 pub fn into_router(self) -> Router {
39 self.try_into_router()
40 .unwrap_or_else(|error| panic!("{error}"))
41 }
42
43 pub fn try_into_router(self) -> Result<Router, RoutePathError> {
45 let prefix = normalize_mount_prefix(&self.prefix)?;
46 let mut router = Router::new();
47 for route in self.routes {
48 let full_path = join_normalized_paths(&prefix, route.path());
52 router = route.mount(router, full_path);
53 }
54 Ok(router)
55 }
56}