1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use cookie::{Cookie, CookieJar};
use trillium::Conn;

/**
Extension trait adding cookie capacities to [`Conn`].

Important: The [`CookiesHandler`](crate::CookiesHandler) must be
called before any of these functions can be called on a conn.
*/
pub trait CookiesConnExt {
    /// adds a cookie to the cookie jar and returns the conn
    fn with_cookie<'a>(self, cookie: impl Into<Cookie<'a>>) -> Self;
    /// gets a reference to the cookie jar
    fn cookies(&self) -> &CookieJar;
    /// gets a mutable reference to the cookie jar
    fn cookies_mut(&mut self) -> &mut CookieJar;
}

impl CookiesConnExt for Conn {
    fn cookies(&self) -> &CookieJar {
        self.state()
            .expect("Cookies handler must be executed before calling CookiesExt::cookies")
    }

    fn with_cookie<'a>(mut self, cookie: impl Into<Cookie<'a>>) -> Self {
        self.cookies_mut().add(cookie.into().into_owned());
        self
    }

    fn cookies_mut(&mut self) -> &mut CookieJar {
        self.state_mut()
            .expect("Cookies handler must be executed before calling CookiesExt::cookies_mut")
    }
}