Skip to main content

trillium_cookies/
cookies_conn_ext.rs

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