Skip to main content

trillium_sessions/
session_conn_ext.rs

1use async_session::{Session, serde::Serialize};
2use trillium::Conn;
3
4/// extension trait to add session support to [`Conn`]
5///
6/// [`SessionHandler`](crate::SessionHandler) **MUST** be called on the
7/// conn prior to using any of these functions.
8pub trait SessionConnExt {
9    /// append a key-value pair to the current session, where the key is a
10    /// &str and the value is anything serde-serializable.
11    fn with_session(self, key: &str, value: impl Serialize) -> Self;
12
13    /// retrieve a reference to the current session
14    fn session(&self) -> &Session;
15
16    /// retrieve a mutable reference to the current session
17    fn session_mut(&mut self) -> &mut Session;
18}
19
20impl SessionConnExt for Conn {
21    fn session(&self) -> &Session {
22        self.state()
23            .expect("SessionHandler must be executed before calling SessionConnExt::sessions")
24    }
25
26    fn with_session(mut self, key: &str, value: impl Serialize) -> Self {
27        self.session_mut().insert(key, value).ok();
28        self
29    }
30
31    fn session_mut(&mut self) -> &mut Session {
32        self.state_mut()
33            .expect("SessionHandler must be executed before calling SessionConnExt::sessions_mut")
34    }
35}