rpc_router/router/
router_builder_macro.rs

1/// A simple macro to create a new RouterBuider from a list of handlers
2/// and optionaly a list of resources
3///
4/// ## Pattern 1 - List of function handlers
5/// ```
6/// router_builder!(
7///   create_project,
8///   list_projects,
9///   update_project,
10///   delete_project
11/// );
12/// ```
13/// Is equivalent to:
14/// ```
15/// RouterBuilder::default()
16///     .append_dyn("create_project", create_project.into_box())
17///     .append_dyn("list_projects", list_projects.into_box())
18///     .append_dyn("update_project", update_project.into_box())
19///     .append_dyn("delete_project", delete_project.into_box())
20/// ```
21///
22/// ## Pattern 2 - List of function handlers, and resources
23/// ```
24/// router_builder!(
25///   handlers: [get_task, create_task],         // will be turned into routes
26///   resources: [ModelManager {}, AiManager {}] // common resources for all calls
27/// );
28/// ```
29///
30/// Is equivalent to:
31///
32/// ```
33/// RouterBuilder::default()
34///     .append_dyn("get_task", get_task.into_box())
35///     .append_dyn("create_task", create_task.into_box())
36///     .append_resource(ModelManager {})
37///     .append_resource(AiManager {})
38/// ```
39///
40/// ## Pattern 3 - Just for consistency with Pattern 2, we can have omit the resources
41///
42/// ```
43/// router_builder!(
44///   handlers: [get_task, create_task]
45/// );
46/// ```
47///
48#[macro_export]
49macro_rules! router_builder {
50	// Pattern 1 - with `rpc_router!(my_fn1, myfn2)`
51    ($($fn_name:ident),+ $(,)?) => {
52        {
53					use rpc_router::{Handler, RouterBuilder};
54
55					let mut builder = RouterBuilder::default();
56					$(
57							builder = builder.append_dyn(stringify!($fn_name), $fn_name.into_dyn());
58					)+
59					builder
60        }
61    };
62
63    // Pattern 2 - `rpc_router!(handlers: [my_fn1, myfn2], resources: [ModelManger {}, AiManager {}])`
64    (handlers: [$($handler:ident),* $(,)?], resources: [$($resource:expr),* $(,)?]) => {{
65        use rpc_router::{Handler, RouterBuilder};
66
67        let mut builder = RouterBuilder::default();
68        $(
69            builder = builder.append_dyn(stringify!($handler), $handler.into_dyn());
70        )*
71        $(
72            builder = builder.append_resource($resource);
73        )*
74        builder
75    }};
76
77    // Pattern 3 - with `rpc_router!(handlers: [my_fn1, myfn2])`
78    (handlers: [$($handler:ident),* $(,)?]) => {{
79        use rpc_router::{Handler, RouterBuilder};
80
81        let mut builder = RouterBuilder::default();
82        $(
83            builder = builder.append_dyn(stringify!($handler), $handler.into_dyn());
84        )*
85        builder
86    }};
87}