-
-
Notifications
You must be signed in to change notification settings - Fork 169
/
session_store.rs
56 lines (50 loc) · 1.57 KB
/
session_store.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use salvo_core::{async_trait, Depot, Request, Response};
use salvo_session::SessionDepotExt;
use super::{Flash, FlashHandler, FlashStore};
#[derive(Debug)]
pub struct SessionStore {
pub name: String,
}
impl Default for SessionStore {
fn default() -> Self {
Self::new()
}
}
impl Into<FlashHandler<SessionStore>> for SessionStore {
fn into(self) -> FlashHandler<SessionStore> {
FlashHandler::new(self)
}
}
impl SessionStore {
/// Create a new `SessionStore`.
pub fn new() -> Self {
Self { name: "_flash".into() }
}
/// Set cookie name.
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
/// Into `FlashHandler`.
pub fn into_handler(self) -> FlashHandler<SessionStore> {
FlashHandler::new(self)
}
}
#[async_trait]
impl FlashStore for SessionStore {
async fn load_flash(&self, _req: &mut Request, depot: &mut Depot) -> Option<Flash> {
depot.session().and_then(|s| s.get::<Flash>(&self.name))
}
async fn save_flash(&self, flash: Flash, depot: &mut Depot, _res: &mut Response) {
if let Err(e) = depot
.session_mut()
.expect("session must be exist")
.insert(&self.name, &flash)
{
tracing::error!(error = ?e, "save flash to session failed");
}
}
async fn clear_flash(&self, depot: &mut Depot, _res: &mut Response) {
depot.session_mut().expect("session must be exist").remove(&self.name);
}
}