Skip to main content

serenade_http/
loader.rs

1//! Bundle (and other) route loaders.
2
3use crate::{HttpError, RouteCollection};
4
5/// Loads routes into a [`RouteCollection`].
6///
7/// Bundles implement this to contribute routes during kernel compile/boot.
8pub trait RouteLoader {
9    /// Appends routes to `collection`.
10    ///
11    /// # Errors
12    ///
13    /// Returns [`HttpError`] when registration fails (duplicate name, invalid path, …).
14    fn load(&self, collection: &mut RouteCollection) -> Result<(), HttpError>;
15}
16
17impl<F> RouteLoader for F
18where
19    F: Fn(&mut RouteCollection) -> Result<(), HttpError>,
20{
21    fn load(&self, collection: &mut RouteCollection) -> Result<(), HttpError> {
22        self(collection)
23    }
24}
25
26/// Runs every loader in order into a fresh collection.
27///
28/// # Errors
29///
30/// Returns the first loader error.
31pub fn load_routes(loaders: &[&dyn RouteLoader]) -> Result<RouteCollection, HttpError> {
32    let mut collection = RouteCollection::new();
33    for loader in loaders {
34        loader.load(&mut collection)?;
35    }
36    Ok(collection)
37}