sa_token_core/session/mod.rs
1// Author: 金书记
2//
3//! Session 管理模块
4
5use std::collections::HashMap;
6use serde::{Deserialize, Serialize};
7use chrono::{DateTime, Utc};
8
9/// Session 对象 | Session Object
10///
11/// 用于存储用户会话数据的对象
12/// Object for storing user session data
13///
14/// # 字段说明 | Field Description
15/// - `id`: Session 唯一标识 | Session unique identifier
16/// - `create_time`: 创建时间 | Creation time
17/// - `data`: 存储的键值对数据 | Stored key-value data
18///
19/// # 使用示例 | Usage Example
20///
21/// ```rust,ignore
22/// let mut session = SaSession::new("session_123");
23/// session.set("username", "张三")?;
24/// session.set("age", 25)?;
25///
26/// let username: Option<String> = session.get("username");
27/// println!("Username: {:?}", username);
28/// ```
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct SaSession {
31 /// Session ID
32 pub id: String,
33
34 /// 创建时间 | Creation time
35 pub create_time: DateTime<Utc>,
36
37 /// 数据存储 | Data storage
38 #[serde(flatten)]
39 pub data: HashMap<String, serde_json::Value>,
40}
41
42impl SaSession {
43 pub fn new(id: impl Into<String>) -> Self {
44 Self {
45 id: id.into(),
46 create_time: Utc::now(),
47 data: HashMap::new(),
48 }
49 }
50
51 /// 设置值 | Set Value
52 ///
53 /// # 参数 | Parameters
54 /// - `key`: 键名 | Key name
55 /// - `value`: 要存储的值 | Value to store
56 ///
57 /// # 返回 | Returns
58 /// - `Ok(())`: 设置成功 | Set successfully
59 /// - `Err`: 序列化失败 | Serialization failed
60 pub fn set<T: Serialize>(&mut self, key: impl Into<String>, value: T) -> Result<(), serde_json::Error> {
61 let json_value = serde_json::to_value(value)?;
62 self.data.insert(key.into(), json_value);
63 Ok(())
64 }
65
66 /// 获取值 | Get Value
67 ///
68 /// # 参数 | Parameters
69 /// - `key`: 键名 | Key name
70 ///
71 /// # 返回 | Returns
72 /// - `Some(value)`: 找到值并成功反序列化 | Found value and deserialized successfully
73 /// - `None`: 键不存在或反序列化失败 | Key not found or deserialization failed
74 pub fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
75 self.data.get(key)
76 .and_then(|v| serde_json::from_value(v.clone()).ok())
77 }
78
79 /// 删除值 | Remove Value
80 ///
81 /// # 参数 | Parameters
82 /// - `key`: 键名 | Key name
83 ///
84 /// # 返回 | Returns
85 /// 被删除的值,如果键不存在则返回 None
86 /// Removed value, or None if key doesn't exist
87 pub fn remove(&mut self, key: &str) -> Option<serde_json::Value> {
88 self.data.remove(key)
89 }
90
91 /// 清空 session | Clear Session
92 ///
93 /// 删除所有存储的数据 | Remove all stored data
94 pub fn clear(&mut self) {
95 self.data.clear();
96 }
97
98 /// 检查 key 是否存在 | Check if Key Exists
99 ///
100 /// # 参数 | Parameters
101 /// - `key`: 键名 | Key name
102 ///
103 /// # 返回 | Returns
104 /// - `true`: 键存在 | Key exists
105 /// - `false`: 键不存在 | Key doesn't exist
106 pub fn has(&self, key: &str) -> bool {
107 self.data.contains_key(key)
108 }
109}