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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use mime::Mime;
use serde::{de::DeserializeOwned, Serialize};
use trillium::{
    Conn,
    KnownHeaderName::{Accept, ContentType},
    Status,
};

use crate::{Error, Result};

/// Extension trait that adds api methods to [`trillium::Conn`]
#[trillium::async_trait]
pub trait ApiConnExt {
    /**
    Sends a json response body. This sets a status code of 200,
    serializes the body with serde_json, sets the content-type to
    application/json, and [halts](trillium::Conn::halt) the
    conn. If serialization fails, a 500 status code is sent as per
    [`trillium::conn_try`]


    ## Examples

    ```
    use trillium_api::{json, ApiConnExt};
    async fn handler(conn: trillium::Conn) -> trillium::Conn {
        conn.with_json(&json!({ "json macro": "is reexported" }))
    }

    # use trillium_testing::prelude::*;
    assert_ok!(
        get("/").on(&handler),
        r#"{"json macro":"is reexported"}"#,
        "content-type" => "application/json"
    );
    ```

    ### overriding status code
    ```
    use trillium_api::ApiConnExt;
    use serde::Serialize;

    #[derive(Serialize)]
    struct ApiResponse {
       string: &'static str,
       number: usize
    }

    async fn handler(conn: trillium::Conn) -> trillium::Conn {
        conn.with_json(&ApiResponse { string: "not the most creative example", number: 100 })
            .with_status(201)
    }

    # use trillium_testing::prelude::*;
    assert_response!(
        get("/").on(&handler),
        Status::Created,
        r#"{"string":"not the most creative example","number":100}"#,
        "content-type" => "application/json"
    );
    ```
    */
    fn with_json(self, response: &impl Serialize) -> Self;

    /**
    Attempts to deserialize a type from the request body, based on the
    request content type.

    By default, both application/json and
    application/x-www-form-urlencoded are supported, and future
    versions may add accepted request content types. Please open an
    issue if you need to accept another content type.


    To exclusively accept application/json, disable default features
    on this crate.

    This sets a status code of Status::Ok if and only if no status
    code has been explicitly set.

    ## Examples

    ### Deserializing to [`Value`]

    ```
    use trillium_api::{ApiConnExt, Value};

    async fn handler(mut conn: trillium::Conn) -> trillium::Conn {
        let value: Value = trillium::conn_try!(conn.deserialize().await, conn);
        conn.with_json(&value)
    }

    # use trillium_testing::prelude::*;
    assert_ok!(
        post("/")
            .with_request_body(r#"key=value"#)
            .with_request_header("content-type", "application/x-www-form-urlencoded")
            .on(&handler),
        r#"{"key":"value"}"#,
        "content-type" => "application/json"
    );

    ```

    ### Deserializing a concrete type

    ```
    use trillium_api::ApiConnExt;

    #[derive(serde::Deserialize)]
    struct KvPair { key: String, value: String }

    async fn handler(mut conn: trillium::Conn) -> trillium::Conn {
        match conn.deserialize().await {
            Ok(KvPair { key, value }) => {
                conn.with_status(201)
                    .with_body(format!("{} is {}", key, value))
                    .halt()
            }

            Err(_) => conn.with_status(422).with_body("nope").halt()
        }
    }

    # use trillium_testing::prelude::*;
    assert_response!(
        post("/")
            .with_request_body(r#"key=name&value=trillium"#)
            .with_request_header("content-type", "application/x-www-form-urlencoded")
            .on(&handler),
        Status::Created,
        r#"name is trillium"#,
    );

    assert_response!(
        post("/")
            .with_request_body(r#"name=trillium"#)
            .with_request_header("content-type", "application/x-www-form-urlencoded")
            .on(&handler),
        Status::UnprocessableEntity,
        r#"nope"#,
    );


    ```

    */
    async fn deserialize<T>(&mut self) -> Result<T>
    where
        T: DeserializeOwned;

    /// Deserializes json without any Accepts header content negotiation
    async fn deserialize_json<T>(&mut self) -> Result<T>
    where
        T: DeserializeOwned;

    /// Serializes the provided body using Accepts header content negotiation
    async fn serialize<T>(&mut self, body: &T) -> Result<()>
    where
        T: Serialize + Sync;

    /// Returns a parsed content type for this conn.
    ///
    /// Note that this function considers a missing content type an error of variant
    /// [`Error::MissingContentType`].
    fn content_type(&self) -> Result<Mime>;
}

#[trillium::async_trait]
impl ApiConnExt for Conn {
    fn with_json(mut self, response: &impl Serialize) -> Self {
        match serde_json::to_string(&response) {
            Ok(body) => {
                if self.status().is_none() {
                    self.set_status(Status::Ok)
                }

                self.response_headers_mut()
                    .try_insert(ContentType, "application/json");

                self.with_body(body)
            }

            Err(error) => self.with_state(Error::from(error)),
        }
    }

    async fn deserialize<T>(&mut self) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let body = self.request_body_string().await?;
        let content_type = self.content_type()?;
        let suffix_or_subtype = content_type
            .suffix()
            .unwrap_or_else(|| content_type.subtype())
            .as_str();
        match suffix_or_subtype {
            "json" => {
                let json_deserializer = &mut serde_json::Deserializer::from_str(&body);
                Ok(serde_path_to_error::deserialize::<_, T>(json_deserializer)?)
            }

            #[cfg(feature = "forms")]
            "x-www-form-urlencoded" => {
                let body = form_urlencoded::parse(body.as_bytes());
                let deserializer = serde_urlencoded::Deserializer::new(body);
                Ok(serde_path_to_error::deserialize::<_, T>(deserializer)?)
            }

            _ => Err(Error::UnsupportedMimeType {
                mime_type: content_type.to_string(),
            }),
        }
    }

    fn content_type(&self) -> Result<Mime> {
        let header_str = self
            .headers()
            .get_str(ContentType)
            .ok_or(Error::MissingContentType)?;

        header_str.parse().map_err(|_| Error::UnsupportedMimeType {
            mime_type: header_str.into(),
        })
    }

    async fn deserialize_json<T>(&mut self) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let content_type = self.content_type()?;
        let suffix_or_subtype = content_type
            .suffix()
            .unwrap_or_else(|| content_type.subtype())
            .as_str();
        if suffix_or_subtype != "json" {
            return Err(Error::UnsupportedMimeType {
                mime_type: content_type.to_string(),
            });
        }

        log::debug!("extracting json");
        let body = self.request_body_string().await?;
        let json_deserializer = &mut serde_json::Deserializer::from_str(&body);
        Ok(serde_path_to_error::deserialize::<_, T>(json_deserializer)?)
    }

    async fn serialize<T>(&mut self, body: &T) -> Result<()>
    where
        T: Serialize + Sync,
    {
        let accept = self
            .headers()
            .get_str(Accept)
            .unwrap_or("*/*")
            .split(',')
            .map(|s| s.trim())
            .find_map(acceptable_mime_type);

        match accept {
            Some(AcceptableMime::Json) => {
                self.set_body(serde_json::to_string(body)?);
                self.headers_mut().insert(ContentType, "application/json");
                Ok(())
            }

            #[cfg(feature = "forms")]
            Some(AcceptableMime::Form) => {
                self.set_body(serde_urlencoded::to_string(body)?);
                self.headers_mut()
                    .insert(ContentType, "application/x-www-form-urlencoded");
                Ok(())
            }

            None => Err(Error::FailureToNegotiateContent),
        }
    }
}

enum AcceptableMime {
    Json,
    #[cfg(feature = "forms")]
    Form,
}

fn acceptable_mime_type(mime: &str) -> Option<AcceptableMime> {
    let mime: Mime = mime.parse().ok()?;
    let suffix_or_subtype = mime.suffix().unwrap_or_else(|| mime.subtype()).as_str();
    match suffix_or_subtype {
        "*" | "json" => Some(AcceptableMime::Json),

        #[cfg(feature = "forms")]
        "x-www-form-urlencoded" => Some(AcceptableMime::Form),

        _ => None,
    }
}