create server_cached function
This commit is contained in:
1 parent
d885846589
commit
de72d85391
8 files changed
+182
-14
No files matched your search
@@ -0,0 +1,56 @@
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use base64::Engine;
|
||||
|
||||
use super::HTMLDataCursor;
|
||||
|
||||
#[allow(unused)]
|
||||
pub(crate) fn serde_from_bytes<T: DeserializeOwned>(string: &[u8]) -> Option<T> {
|
||||
let decompressed = STANDARD.decode(string).ok()?;
|
||||
|
||||
postcard::from_bytes(&decompressed).ok()
|
||||
}
|
||||
|
||||
static SERVER_DATA: once_cell::sync::Lazy<Option<HTMLDataCursor>> =
|
||||
once_cell::sync::Lazy::new(|| {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let attribute = web_sys::window()?
|
||||
.document()?
|
||||
.get_element_by_id("dioxus-storage-data")?
|
||||
.get_attribute("data-serialized")?;
|
||||
|
||||
let data: super::HTMLData = serde_from_bytes(attribute.as_bytes())?;
|
||||
|
||||
Some(data.cursor())
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
});
|
||||
|
||||
pub(crate) fn take_server_data<T: DeserializeOwned>() -> Option<T> {
|
||||
SERVER_DATA.as_ref()?.take()
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "ssr"))]
|
||||
/// Get the props from the document. This is only available in the browser.
|
||||
///
|
||||
/// When dioxus-fullstack renders the page, it will serialize the root props and put them in the document. This function gets them from the document.
|
||||
pub fn get_root_props_from_document<T: DeserializeOwned>() -> Option<T> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let attribute = web_sys::window()?
|
||||
.document()?
|
||||
.get_element_by_id("dioxus-storage-props")?
|
||||
.get_attribute("data-serialized")?;
|
||||
|
||||
serde_from_bytes(attribute.as_bytes())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user