sa_token_core/session/
mod.rs1use std::collections::HashMap;
6use serde::{Deserialize, Serialize};
7use chrono::{DateTime, Utc};
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct SaSession {
12 pub id: String,
14
15 pub create_time: DateTime<Utc>,
17
18 #[serde(flatten)]
20 pub data: HashMap<String, serde_json::Value>,
21}
22
23impl SaSession {
24 pub fn new(id: impl Into<String>) -> Self {
25 Self {
26 id: id.into(),
27 create_time: Utc::now(),
28 data: HashMap::new(),
29 }
30 }
31
32 pub fn set<T: Serialize>(&mut self, key: impl Into<String>, value: T) -> Result<(), serde_json::Error> {
34 let json_value = serde_json::to_value(value)?;
35 self.data.insert(key.into(), json_value);
36 Ok(())
37 }
38
39 pub fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
41 self.data.get(key)
42 .and_then(|v| serde_json::from_value(v.clone()).ok())
43 }
44
45 pub fn remove(&mut self, key: &str) -> Option<serde_json::Value> {
47 self.data.remove(key)
48 }
49
50 pub fn clear(&mut self) {
52 self.data.clear();
53 }
54
55 pub fn has(&self, key: &str) -> bool {
57 self.data.contains_key(key)
58 }
59}