use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SaSession {
pub id: String,
pub create_time: DateTime<Utc>,
#[serde(flatten)]
pub data: HashMap<String, serde_json::Value>,
}
impl SaSession {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
create_time: Utc::now(),
data: HashMap::new(),
}
}
pub fn set<T: Serialize>(&mut self, key: impl Into<String>, value: T) -> Result<(), serde_json::Error> {
let json_value = serde_json::to_value(value)?;
self.data.insert(key.into(), json_value);
Ok(())
}
pub fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
self.data.get(key)
.and_then(|v| serde_json::from_value(v.clone()).ok())
}
pub fn remove(&mut self, key: &str) -> Option<serde_json::Value> {
self.data.remove(key)
}
pub fn clear(&mut self) {
self.data.clear();
}
pub fn has(&self, key: &str) -> bool {
self.data.contains_key(key)
}
}