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