Skip to main content

trillium_sessions/
session_conn_ext.rs

1use crate::SessionStoreError;
2use async_session::{Session, serde::Serialize};
3use trillium::Conn;
4
5/// extension trait to add session support to [`Conn`]
6///
7/// [`SessionHandler`](crate::SessionHandler) **MUST** be called on the
8/// conn prior to using any of these functions.
9pub trait SessionConnExt {
10    /// append a key-value pair to the current session, where the key is a
11    /// &str and the value is anything serde-serializable.
12    fn with_session(self, key: &str, value: impl Serialize) -> Self;
13
14    /// retrieve a reference to the current session
15    fn session(&self) -> &Session;
16
17    /// retrieve a mutable reference to the current session
18    fn session_mut(&mut self) -> &mut Session;
19
20    /// retrieve the error returned by the session store, if this request's session could not be
21    /// loaded
22    ///
23    /// This is only ever present when the handler provided to
24    /// [`SessionHandler::with_store_error_handler`](crate::SessionHandler::with_store_error_handler)
25    /// did not halt.
26    fn session_store_error(&self) -> Option<&SessionStoreError>;
27}
28
29impl SessionConnExt for Conn {
30    fn session(&self) -> &Session {
31        self.state()
32            .expect("SessionHandler must be executed before calling SessionConnExt::sessions")
33    }
34
35    fn with_session(mut self, key: &str, value: impl Serialize) -> Self {
36        self.session_mut().insert(key, value).ok();
37        self
38    }
39
40    fn session_mut(&mut self) -> &mut Session {
41        self.state_mut()
42            .expect("SessionHandler must be executed before calling SessionConnExt::sessions_mut")
43    }
44
45    fn session_store_error(&self) -> Option<&SessionStoreError> {
46        self.state()
47    }
48}