use std::{cell::Cell, rc::Rc};
use vertigo_macro::store;
use crate::{
dev::{SsrFetchCache, SsrFetchRequest, SsrFetchResponse},
struct_mut::ValueMut,
};
use super::api_browser_command;
#[store]
pub fn api_fetch_cache() -> Rc<FetchCache> {
Rc::new(FetchCache {
cache: ValueMut::new(None),
})
}
thread_local! {
static CLOSED: Cell<bool> = const { Cell::new(false) };
}
pub fn close_fetch_cache() {
CLOSED.with(|closed| closed.set(true));
}
pub struct FetchCache {
cache: ValueMut<Option<Rc<SsrFetchCache>>>,
}
impl FetchCache {
pub fn get_response(&self, request: &SsrFetchRequest) -> Option<SsrFetchResponse> {
if CLOSED.with(Cell::get) {
return None;
}
let cache = match self.cache.get() {
Some(cache) => cache,
None => {
let cache = Rc::new(api_browser_command().fetch_cache_get());
self.cache.set(Some(cache.clone()));
cache
}
};
cache.get(request).cloned()
}
}
#[cfg(test)]
pub fn ssr_fetched(url: &str, status: u32, body: crate::JsJson) {
use crate::{
JsJsonSerialize, RequestBuilder, dev::SsrFetchResponseContent,
external_api::safe_wrappers::TEST_FETCH_CACHE,
};
use std::collections::BTreeMap;
let request = RequestBuilder::get(url).to_request(None);
let response = SsrFetchResponse::Ok {
status,
response: SsrFetchResponseContent::Json(body),
};
let cache = SsrFetchCache::new(&BTreeMap::from([(request, response)]));
TEST_FETCH_CACHE.with(|stored| {
*stored.borrow_mut() = Some(cache.to_json().convert_to_string());
});
}