37
crates/como_domain/src/common/mod.rs
Normal file
37
crates/como_domain/src/common/mod.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
pub mod user;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Context {
|
||||
values: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
values: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_value(&self, key: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
let mut values = self.values.clone();
|
||||
|
||||
let _ = values.insert(key.into(), value.into());
|
||||
|
||||
Self { values }
|
||||
}
|
||||
|
||||
pub fn with_value_mut(
|
||||
&mut self,
|
||||
key: impl Into<String>,
|
||||
value: impl Into<String>,
|
||||
) -> &mut Self {
|
||||
self.values.insert(key.into(), value.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn get(&self, key: impl AsRef<str>) -> Option<&str> {
|
||||
self.values.get(key.as_ref()).map(|s| s.as_str())
|
||||
}
|
||||
}
|
23
crates/como_domain/src/common/user.rs
Normal file
23
crates/como_domain/src/common/user.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use crate::Context;
|
||||
|
||||
pub trait ContextUserExt {
|
||||
fn set_user_id(&self, user_id: impl Into<String>) -> Context;
|
||||
fn set_user_id_mut(&mut self, user_id: impl Into<String>) -> &mut Context;
|
||||
fn get_user_id(&self) -> Option<String>;
|
||||
}
|
||||
|
||||
const USER_ID_KEY: &str = "user_id";
|
||||
|
||||
impl ContextUserExt for Context {
|
||||
fn set_user_id(&self, user_id: impl Into<String>) -> Context {
|
||||
self.with_value(USER_ID_KEY, user_id)
|
||||
}
|
||||
|
||||
fn set_user_id_mut(&mut self, user_id: impl Into<String>) -> &mut Context {
|
||||
self.with_value_mut(USER_ID_KEY, user_id)
|
||||
}
|
||||
|
||||
fn get_user_id(&self) -> Option<String> {
|
||||
self.get(USER_ID_KEY).map(|s| s.to_string())
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user