salvo_flash/
session_store.rs

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