1use crate::utils::APIFunction;
24use crate::{APIPath, FormData, HTMLResult, RUMWebData, SharedAppState};
25use rumtk_core::cache::{new_cache, LazyRUMCache, LazyRUMCacheValue};
26use rumtk_core::strings::{rumtk_format, RUMString};
27use rumtk_core::{rumtk_cache_get, rumtk_cache_push};
28
29pub type APICache = LazyRUMCache<RUMString, APIFunction>;
30pub type APIItem<'a> = (&'a str, APIFunction);
31pub type UserAPIEndpoints<'a> = Vec<APIItem<'a>>;
32pub type APICacheItem = LazyRUMCacheValue<APIFunction>;
33
34static mut API_CACHE: APICache = new_cache();
35const DEFAULT_API_HANDLER: APIFunction =
36 |path: APIPath, params: RUMWebData, form: FormData, state: SharedAppState| -> HTMLResult {
37 Err(rumtk_format!(
38 "No handler registered for API endpoint => {}",
39 path
40 ))
41 };
42
43pub fn register_api_endpoint(name: &str, api_handler: APIFunction) -> APICacheItem {
44 let key = RUMString::from(name);
45 let r = rumtk_cache_push!(&raw mut API_CACHE, &key, &api_handler);
46
47 println!(
48 " ➡ Registered api endpoint {} => api function [{:?}]",
49 name, &api_handler
50 );
51 r
52}
53
54pub fn get_endpoint(name: &str) -> APICacheItem {
55 rumtk_cache_get!(
56 &raw mut API_CACHE,
57 &RUMString::from(name),
58 get_default_api_handler()
59 )
60}
61
62pub fn get_default_api_handler() -> &'static APIFunction {
63 &DEFAULT_API_HANDLER
64}
65
66pub fn init_endpoints(user_components: &UserAPIEndpoints) {
67 println!("🌩 Registering API Endpoints! 🌩");
68 for (name, value) in user_components {
70 let _ = register_api_endpoint(name, *value);
71 }
72 println!("🌩 ~~~~~~~~~~~~~~~~~~~~~~ 🌩");
73}
74
75#[macro_export]
76macro_rules! rumtk_web_register_api {
77 ( $key:expr, $fxn:expr ) => {{
78 use $crate::api::register_api_endpoint;
79 register_api_endpoint($key, $fxn)
80 }};
81}
82
83#[macro_export]
84macro_rules! rumtk_web_get_api_endpoint {
85 ( $key:expr ) => {{
86 use $crate::api::get_endpoint;
87 get_endpoint($key)
88 }};
89}
90
91#[macro_export]
92macro_rules! rumtk_web_init_api_endpoints {
93 ( $pages:expr ) => {{
94 use $crate::api::init_endpoints;
95 init_endpoints($pages)
96 }};
97}