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