|
| 1 | +//! Allows use of the Web Storage API including both local and session storage. |
| 2 | +//! |
| 3 | +//! # References |
| 4 | +//! * [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/Storage) |
| 5 | +//! * [web-sys docs](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Storage.html) |
| 6 | +//! * [Example syntax](https://github.com/rustwasm/wasm-bindgen/blob/master/examples/todomvc/src/store.rs) |
| 7 | +
|
| 8 | +extern crate serde; |
| 9 | +extern crate serde_json; |
| 10 | +use crate::browser::util::window; |
| 11 | +use web_sys::Storage; |
| 12 | + |
| 13 | +pub type JsValue = wasm_bindgen::JsValue; |
| 14 | + |
| 15 | +pub enum Mechanism { |
| 16 | + LocalStorage, |
| 17 | + SessionStorage, |
| 18 | +} |
| 19 | + |
| 20 | +pub struct WebStorage { |
| 21 | + pub mechanism: Mechanism, |
| 22 | + storage: Storage, |
| 23 | +} |
| 24 | + |
| 25 | +/// Things that can go wrong when trying to load data from storage. |
| 26 | +pub enum LoadError { |
| 27 | + /// Could not connect to storage. |
| 28 | + CouldNotConnect(JsValue), |
| 29 | + /// The data could not be decoded from JSON. |
| 30 | + CouldNotDecode(serde_json::Error), |
| 31 | + /// There is no data for that key. |
| 32 | + NoData, |
| 33 | +} |
| 34 | + |
| 35 | +/// Things that can go wrong when trying to save data to storage. |
| 36 | +pub enum SaveError { |
| 37 | + /// The browser denied saving to storage. Usually because the storage is full. |
| 38 | + /// See: https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions |
| 39 | + CouldNotSave(JsValue), |
| 40 | + /// Supplied data could not be encoded to json. |
| 41 | + CouldNotEncode(serde_json::Error), |
| 42 | +} |
| 43 | + |
| 44 | +impl WebStorage { |
| 45 | + /// Clear all data in storage |
| 46 | + pub fn clear(&self) -> bool { |
| 47 | + self.storage.clear().is_ok() |
| 48 | + } |
| 49 | + |
| 50 | + /// A vector of all the keys in storage |
| 51 | + /// |
| 52 | + /// # Errors |
| 53 | + /// |
| 54 | + /// Will return a `Err(JsValue)` if the storage length could not be retrieved. |
| 55 | + pub fn keys(storage: &Storage) -> Result<Vec<String>, JsValue> { |
| 56 | + let mut keys = vec![]; |
| 57 | + let length = storage.length()?; |
| 58 | + for index in 0..length { |
| 59 | + if let Ok(Some(key)) = storage.key(index) { |
| 60 | + keys.push(key); |
| 61 | + } |
| 62 | + } |
| 63 | + Ok(keys) |
| 64 | + } |
| 65 | + |
| 66 | + /// Load a JSON deserializable data structure from storage. |
| 67 | + /// |
| 68 | + /// # Errors |
| 69 | + /// |
| 70 | + /// Will return a `Err(LoadError)` if the data could not be loaded |
| 71 | + pub fn load<T>(&self, key: &str) -> Result<T, LoadError> |
| 72 | + where |
| 73 | + T: serde::de::DeserializeOwned, |
| 74 | + { |
| 75 | + let item = self |
| 76 | + .storage |
| 77 | + .get_item(key) |
| 78 | + .map_err(LoadError::CouldNotConnect)?; |
| 79 | + |
| 80 | + match item { |
| 81 | + None => Err(LoadError::NoData), |
| 82 | + Some(d) => { |
| 83 | + let decoded = serde_json::from_str(&d); |
| 84 | + decoded.map_err(LoadError::CouldNotDecode) |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + /// Delete a key and associated data from storage |
| 90 | + pub fn delete(&self, key: &str) -> bool { |
| 91 | + self.storage.remove_item(key).is_ok() |
| 92 | + } |
| 93 | + |
| 94 | + /// Save a JSON serializable data structure to storage. |
| 95 | + /// |
| 96 | + /// # Errors |
| 97 | + /// |
| 98 | + /// Will return a `SaveError` if the data could not be saved |
| 99 | + pub fn save<T>(&self, key: &str, data: &T) -> Result<(), SaveError> |
| 100 | + where |
| 101 | + T: serde::Serialize, |
| 102 | + { |
| 103 | + let serialized = serde_json::to_string(&data).map_err(SaveError::CouldNotEncode)?; |
| 104 | + self.storage |
| 105 | + .set_item(key, &serialized) |
| 106 | + .map_err(SaveError::CouldNotSave) |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +/// Get an instance of Local Storage |
| 111 | +/// Local Storage maintains a storage area that persists even when the browser |
| 112 | +/// is closed and reopened |
| 113 | +pub fn get_local_storage() -> Option<WebStorage> { |
| 114 | + window() |
| 115 | + .local_storage() |
| 116 | + .unwrap_or(None) |
| 117 | + .map(|storage| WebStorage { |
| 118 | + mechanism: Mechanism::LocalStorage, |
| 119 | + storage, |
| 120 | + }) |
| 121 | +} |
| 122 | + |
| 123 | +/// Get an instance of Session Storage |
| 124 | +/// Session Storage maintains a storage area for the duration of the page session |
| 125 | +/// (as long as the browser is open, including page reloads and restores) |
| 126 | +pub fn get_session_storage() -> Option<WebStorage> { |
| 127 | + window() |
| 128 | + .session_storage() |
| 129 | + .unwrap_or(None) |
| 130 | + .map(|storage| WebStorage { |
| 131 | + mechanism: Mechanism::SessionStorage, |
| 132 | + storage, |
| 133 | + }) |
| 134 | +} |
0 commit comments