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    #[must_use]
22    pub fn new() -> Self {
23        Self {
24            name: "salvo.flash".into(),
25        }
26    }
27
28    /// Sets session key name.
29    #[must_use]
30    pub fn name(mut self, name: impl Into<String>) -> Self {
31        self.name = name.into();
32        self
33    }
34
35    /// Converts into `FlashHandler`.
36    #[must_use]
37    pub fn into_handler(self) -> FlashHandler<Self> {
38        FlashHandler::new(self)
39    }
40}
41
42impl FlashStore for SessionStore {
43    async fn load_flash(&self, _req: &mut Request, depot: &mut Depot) -> Option<Flash> {
44        depot.session().and_then(|s| s.get::<Flash>(&self.name))
45    }
46    async fn save_flash(&self, _req: &mut Request, depot: &mut Depot, _res: &mut Response, flash: Flash) {
47        if let Err(e) = depot
48            .session_mut()
49            .expect("session must exist")
50            .insert(&self.name, flash)
51        {
52            tracing::error!(error = ?e, "save flash to session failed");
53        }
54    }
55    async fn clear_flash(&self, depot: &mut Depot, _res: &mut Response) {
56        depot.session_mut().expect("session must exist").remove(&self.name);
57    }
58}