doido_controller/
flash.rs1use crate::session::{CookieSessionStore, Session};
9use std::collections::BTreeMap;
10
11#[derive(Debug, Default, Clone)]
13pub struct Flash {
14 messages: BTreeMap<String, String>,
15}
16
17impl Flash {
18 pub fn new() -> Self {
19 Self::default()
20 }
21
22 pub fn set(&mut self, key: impl Into<String>, message: impl Into<String>) {
24 self.messages.insert(key.into(), message.into());
25 }
26
27 pub fn get(&self, key: &str) -> Option<&str> {
29 self.messages.get(key).map(String::as_str)
30 }
31
32 pub fn is_empty(&self) -> bool {
34 self.messages.is_empty()
35 }
36
37 pub fn iter(&self) -> impl Iterator<Item = (&String, &String)> {
39 self.messages.iter()
40 }
41
42 pub fn to_cookie(&self, store: &CookieSessionStore) -> String {
44 let mut session = Session::with_id("flash");
45 session.set("flash", &self.messages);
46 store.encode(&session)
47 }
48
49 pub fn from_cookie(store: &CookieSessionStore, raw: &str) -> Self {
52 let messages = store
53 .decode(raw)
54 .and_then(|s| s.get::<BTreeMap<String, String>>("flash"))
55 .unwrap_or_default();
56 Self { messages }
57 }
58}