Skip to main content

trillium_sessions/
session_conn_ext.rs

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