Skip to main content

trillium_api/
from_conn.rs

1use crate::TryFromConn;
2use trillium::{async_trait, Conn};
3
4/// A trait to extract content from [`Conn`]s to be used as the second
5/// argument to an api handler. Implement this for your types.
6#[async_trait]
7pub trait FromConn: Send + Sync + Sized + 'static {
8    /// returning None from this will not call the api handler, but
9    /// will halt the conn.
10    async fn from_conn(conn: &mut Conn) -> Option<Self>;
11}
12
13#[async_trait]
14impl FromConn for () {
15    async fn from_conn(_: &mut Conn) -> Option<Self> {
16        Some(())
17    }
18}
19
20#[async_trait]
21impl<E: FromConn> FromConn for Option<E> {
22    async fn from_conn(conn: &mut Conn) -> Option<Self> {
23        Some(E::from_conn(conn).await)
24    }
25}
26
27#[async_trait]
28impl<T, E> FromConn for Result<T, E>
29where
30    T: TryFromConn<Error = E>,
31    E: Send + Sync + 'static,
32{
33    async fn from_conn(conn: &mut Conn) -> Option<Self> {
34        Some(T::try_from_conn(conn).await)
35    }
36}
37
38#[async_trait]
39impl FromConn for trillium::Headers {
40    async fn from_conn(conn: &mut Conn) -> Option<Self> {
41        Some(conn.request_headers().clone())
42    }
43}
44
45#[async_trait]
46impl FromConn for trillium::Method {
47    async fn from_conn(conn: &mut Conn) -> Option<Self> {
48        Some(conn.method())
49    }
50}