Skip to main content

trillium_cookies/
cookies_conn_ext.rs

1use cookie::{Cookie, CookieJar};
2use trillium::Conn;
3
4/// Extension trait adding cookie capacities to [`Conn`].
5///
6/// Important: The [`CookiesHandler`](crate::CookiesHandler) must be
7/// called before any of these functions can be called on a conn.
8pub trait CookiesConnExt {
9    /// adds a cookie to the cookie jar and returns the conn
10    fn with_cookie<'a>(self, cookie: impl Into<Cookie<'a>>) -> Self;
11    /// gets a reference to the cookie jar
12    fn cookies(&self) -> &CookieJar;
13    /// gets a mutable reference to the cookie jar
14    fn cookies_mut(&mut self) -> &mut CookieJar;
15}
16
17impl CookiesConnExt for Conn {
18    fn cookies(&self) -> &CookieJar {
19        self.state()
20            .expect("Cookies handler must be executed before calling CookiesExt::cookies")
21    }
22
23    fn with_cookie<'a>(mut self, cookie: impl Into<Cookie<'a>>) -> Self {
24        self.cookies_mut().add(cookie.into().into_owned());
25        self
26    }
27
28    fn cookies_mut(&mut self) -> &mut CookieJar {
29        self.state_mut()
30            .expect("Cookies handler must be executed before calling CookiesExt::cookies_mut")
31    }
32}