You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.8 KiB
59 lines
1.8 KiB
use serde_json::Value;
|
|
use serde::de::DeserializeOwned;
|
|
use serde::Serialize;
|
|
use json_dotpath::DotPaths;
|
|
|
|
pub type Session<'a> = rocket_session::Session<'a, serde_json::Map<String, Value>>;
|
|
|
|
pub trait SessionAccess {
|
|
fn get<T: DeserializeOwned>(&self, path: &str) -> Option<T>;
|
|
|
|
fn get_or<T: DeserializeOwned>(&self, path: &str, def: T) -> T;
|
|
|
|
fn get_or_else<T: DeserializeOwned, F: FnOnce() -> T>(&self, path: &str, def: F) -> T;
|
|
|
|
fn get_or_default<T: DeserializeOwned + Default>(&self, path: &str) -> T;
|
|
|
|
fn take<T: DeserializeOwned>(&self, path: &str) -> Option<T>;
|
|
|
|
fn replace<O: DeserializeOwned, N: Serialize>(&self, path: &str, new: N) -> Option<O>;
|
|
|
|
fn set<T: Serialize>(&self, path: &str, value: T);
|
|
|
|
fn remove(&self, path: &str) -> bool;
|
|
}
|
|
|
|
impl<'a> SessionAccess for Session<'a> {
|
|
fn get<T: DeserializeOwned>(&self, path: &str) -> Option<T> {
|
|
self.tap(|data| data.dot_get(path))
|
|
}
|
|
|
|
fn get_or<T: DeserializeOwned>(&self, path: &str, def: T) -> T {
|
|
self.get(path).unwrap_or(def)
|
|
}
|
|
|
|
fn get_or_else<T: DeserializeOwned, F: FnOnce() -> T>(&self, path: &str, def: F) -> T {
|
|
self.get(path).unwrap_or_else(def)
|
|
}
|
|
|
|
fn get_or_default<T: DeserializeOwned + Default>(&self, path: &str) -> T {
|
|
self.get(path).unwrap_or_default()
|
|
}
|
|
|
|
fn take<T: DeserializeOwned>(&self, path: &str) -> Option<T> {
|
|
self.tap(|data| data.dot_take(path))
|
|
}
|
|
|
|
fn replace<O: DeserializeOwned, N: Serialize>(&self, path: &str, new: N) -> Option<O> {
|
|
self.tap(|data| data.dot_replace(path, new))
|
|
}
|
|
|
|
fn set<T: Serialize>(&self, path: &str, value: T) {
|
|
self.tap(|data| data.dot_set(path, value));
|
|
}
|
|
|
|
fn remove(&self, path: &str) -> bool {
|
|
self.tap(|data| data.dot_remove(path))
|
|
}
|
|
}
|
|
|
|
|