use crate::prelude::*;
use crate::utils::{window, ResultExt};
use std::io;
#[derive(Debug)]
pub struct LocalStorage {
storage: web_sys::Storage,
}
impl LocalStorage {
pub fn open() -> io::Result<Self> {
match window().local_storage() {
Ok(Some(storage)) => Ok(Self { storage }),
_ => Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Unable to access local Storage object.",
)),
}
}
pub fn len(&self) -> usize {
self.storage.length().unwrap_throw() as usize
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn clear(&self) {
self.storage.clear().unwrap_throw()
}
pub fn insert(&self, key: &str, val: &str) -> io::Result<()> {
self.storage
.set_item(key, val)
.err_kind(io::ErrorKind::Other)
}
pub fn remove(&self, key: &str) -> Option<String> {
let val = self.get(key);
self.storage.remove_item(key).unwrap_throw();
val
}
pub fn get(&self, key: &str) -> Option<String> {
self.storage.get_item(key).ok().flatten()
}
}