salvo_flash/
session_store.rs1use salvo_core::{Depot, Request, Response};
2use salvo_session::SessionDepotExt;
3
4use super::{Flash, FlashHandler, FlashStore};
5
6#[derive(Debug)]
8#[non_exhaustive]
9pub struct SessionStore {
10 pub name: String,
12}
13impl Default for SessionStore {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl SessionStore {
20 #[must_use]
22 pub fn new() -> Self {
23 Self {
24 name: "salvo.flash".into(),
25 }
26 }
27
28 #[must_use]
30 pub fn name(mut self, name: impl Into<String>) -> Self {
31 self.name = name.into();
32 self
33 }
34
35 #[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}