Skip to main content

nidus_http/
controller.rs

1//! Controller metadata.
2
3use axum::Router;
4
5use crate::error::RoutePathError;
6use crate::router::{RouteDefinition, join_normalized_paths, normalize_mount_prefix};
7
8/// Controller route group with a shared path prefix.
9pub struct Controller {
10    prefix: String,
11    routes: Vec<RouteDefinition>,
12}
13
14impl Controller {
15    /// Creates an empty controller route group.
16    pub fn new(prefix: impl Into<String>) -> Self {
17        Self {
18            prefix: prefix.into(),
19            routes: Vec::new(),
20        }
21    }
22
23    /// Tries to create an empty controller route group with a validated prefix.
24    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    /// Adds a route to this controller.
32    pub fn route(mut self, route: RouteDefinition) -> Self {
33        self.routes.push(route);
34        self
35    }
36
37    /// Builds an Axum router from the controller routes.
38    pub fn into_router(self) -> Router {
39        self.try_into_router()
40            .unwrap_or_else(|error| panic!("{error}"))
41    }
42
43    /// Tries to build an Axum router from the controller routes.
44    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            // RouteDefinition normalizes its path at construction, so only the
49            // controller prefix needs validation here. Avoid re-normalizing
50            // both strings for every route in the controller.
51            let full_path = join_normalized_paths(&prefix, route.path());
52            router = route.mount(router, full_path);
53        }
54        Ok(router)
55    }
56}