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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use crate::{ApiConnExt, FromConn};
use trillium::{async_trait, Conn, Handler};
/// Like FromConn, but with an Error.
///
/// If you want to use this directly, Error needs to be Handler.
///
/// If Error is not Handler, you can use `Result<T, E> as TryFromConn where T: TryFromConn<Error = E>`
///
/// If extraction is infallible, implement [`FromConn`].
#[async_trait]
pub trait TryFromConn: Send + Sync + Sized + 'static {
    /// The Error type. Tf this is a Handler, you can extract Self directly in a ApiHandler
    /// signature, and Error will be called on Conn if try_from_conn fails.
    type Error: Send + Sync + Sized + 'static;

    /// Attempt to extract Self from &mut Conn, returning Error in case of failure
    async fn try_from_conn(conn: &mut Conn) -> Result<Self, Self::Error>;
}

#[async_trait]
impl TryFromConn for serde_json::Value {
    type Error = crate::Error;
    async fn try_from_conn(conn: &mut Conn) -> Result<Self, Self::Error> {
        conn.deserialize().await
    }
}

#[async_trait]
impl<T: FromConn> TryFromConn for T {
    type Error = ();

    async fn try_from_conn(conn: &mut Conn) -> Result<Self, Self::Error> {
        Self::from_conn(conn).await.ok_or(())
    }
}

#[async_trait]
impl TryFromConn for Vec<u8> {
    type Error = crate::Error;
    async fn try_from_conn(conn: &mut Conn) -> Result<Self, Self::Error> {
        conn.request_body()
            .await
            .read_bytes()
            .await
            .map_err(Into::into)
    }
}

#[async_trait]
impl TryFromConn for String {
    type Error = crate::Error;
    async fn try_from_conn(conn: &mut Conn) -> Result<Self, Self::Error> {
        conn.request_body_string().await.map_err(Into::into)
    }
}

#[cfg(feature = "url")]
#[async_trait]
impl TryFromConn for url::Url {
    type Error = trillium::Status;
    async fn try_from_conn(conn: &mut Conn) -> Result<Self, Self::Error> {
        let path = conn.path();
        let host = conn
            .request_headers()
            .get_str(trillium::KnownHeaderName::Host)
            .ok_or(trillium::Status::BadRequest)?;
        let proto = if conn.is_secure() { "https" } else { "http" };
        url::Url::parse(&format!("{proto}://{host}{path}"))
            .map_err(|_| trillium::Status::BadRequest)
    }
}

macro_rules! impl_try_from_conn_tuple {
    ($($name:ident)+) => (
        #[async_trait]
        impl<$($name),*> TryFromConn for ($($name,)*) where $($name: TryFromConn, <$name as TryFromConn>::Error: Handler),* {
            type Error = Box<dyn Handler>;
            #[allow(non_snake_case)]
            async fn try_from_conn(conn: &mut Conn) -> Result<Self, Self::Error> {
                $(let $name = <$name as TryFromConn>::try_from_conn(conn)
                  .await
                  .map_err(|h| Box::new(h) as Box<dyn Handler>)?;)*
                Ok(($($name, )*))
            }
        }
    )
}

impl_try_from_conn_tuple! { A B }
impl_try_from_conn_tuple! { A B C }
impl_try_from_conn_tuple! { A B C D }
impl_try_from_conn_tuple! { A B C D E }
impl_try_from_conn_tuple! { A B C D E F }
impl_try_from_conn_tuple! { A B C D E F G }
impl_try_from_conn_tuple! { A B C D E F G H }
impl_try_from_conn_tuple! { A B C D E F G H I }
impl_try_from_conn_tuple! { A B C D E F G H I J }
impl_try_from_conn_tuple! { A B C D E F G H I J K }
impl_try_from_conn_tuple! { A B C D E F G H I J K L }