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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
use crate::{Error, Result};
use mime::Mime;
use serde::{Serialize, de::DeserializeOwned};
use std::future::Future;
#[cfg(any(feature = "serde_json", feature = "sonic-rs"))]
use trillium::Status;
use trillium::{
Conn,
KnownHeaderName::{Accept, ContentType},
};
/// Extension trait that adds api methods to [`trillium::Conn`]
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
///
/// ```
/// # if !cfg!(any(feature = "sonic-rs", feature = "serde_json")) { return }
/// use trillium_api::{json, ApiConnExt};
/// use trillium_testing::TestServer;
///
/// async fn handler(conn: trillium::Conn) -> trillium::Conn {
/// conn.with_json(&json!({ "json macro": "is reexported" }))
/// }
///
/// # trillium_testing::block_on(async {
/// let app = TestServer::new(handler).await;
/// app.get("/")
/// .await
/// .assert_ok()
/// .assert_body(r#"{"json macro":"is reexported"}"#)
/// .assert_header("content-type", "application/json");
/// # });
/// ```
///
/// ### overriding status code
/// ```
/// use serde::Serialize;
/// use trillium_api::ApiConnExt;
/// use trillium_testing::TestServer;
///
/// #[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)
/// }
///
/// # trillium_testing::block_on(async {
/// let app = TestServer::new(handler).await;
/// app.get("/")
/// .await
/// .assert_status(201)
/// .assert_body(r#"{"string":"not the most creative example","number":100}"#)
/// .assert_header("content-type", "application/json");
/// # });
/// ```
#[cfg(any(feature = "sonic-rs", feature = "serde_json"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "sonic-rs", feature = "serde_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`
///
/// ```no_run
/// # if !cfg!(any(feature = "sonic-rs", feature = "serde_json")) { return }
/// use trillium_api::{ApiConnExt, Value};
///
/// async fn handler(mut conn: trillium::Conn) -> trillium::Conn {
/// let value: Value = match conn.deserialize().await {
/// Ok(v) => v,
/// Err(_) => return conn.with_status(400),
/// };
/// conn.with_json(&value)
/// }
///
/// # use trillium_testing::TestServer;
/// # trillium_testing::block_on(async {
/// let app = TestServer::new(handler).await;
/// app.post("/")
/// .with_body(r#"key=value"#)
/// .with_request_header("content-type", "application/x-www-form-urlencoded")
/// .await
/// .assert_ok()
/// .assert_body(r#"{"key":"value"}"#)
/// .assert_header("content-type", "application/json");
/// # });
/// ```
///
/// ### Deserializing a concrete type
///
/// ```
/// use trillium_api::ApiConnExt;
/// use trillium_testing::TestServer;
///
/// #[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(),
/// }
/// }
///
/// # trillium_testing::block_on(async {
/// let app = TestServer::new(handler).await;
///
/// app.post("/")
/// .with_body(r#"key=name&value=trillium"#)
/// .with_request_header("content-type", "application/x-www-form-urlencoded")
/// .await
/// .assert_status(201)
/// .assert_body(r#"name is trillium"#);
///
/// app.post("/")
/// .with_body(r#"name=trillium"#)
/// .with_request_header("content-type", "application/x-www-form-urlencoded")
/// .await
/// .assert_status(422)
/// .assert_body(r#"nope"#);
/// # });
/// ```
fn deserialize<T>(&mut self) -> impl Future<Output = Result<T>> + Send
where
T: DeserializeOwned;
/// Deserializes json without any Accepts header content negotiation
#[cfg(any(feature = "sonic-rs", feature = "serde_json"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "sonic-rs", feature = "serde_json"))))]
fn deserialize_json<T>(&mut self) -> impl Future<Output = Result<T>> + Send
where
T: DeserializeOwned;
/// Serializes the provided body using Accepts header content negotiation
fn serialize<T>(&mut self, body: &T) -> impl Future<Output = Result<()>> + Send
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>;
}
impl ApiConnExt for Conn {
#[cfg(any(feature = "sonic-rs", feature = "serde_json"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "sonic-rs", feature = "serde_json"))))]
fn with_json(mut self, response: &impl Serialize) -> Self {
#[cfg(feature = "serde_json")]
let as_string = serde_json::to_string(&response);
#[cfg(feature = "sonic-rs")]
let as_string = sonic_rs::to_string(&response);
match as_string {
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 {
#[cfg(feature = "serde_json")]
"json" => {
let json_deserializer = &mut serde_json::Deserializer::from_str(&body);
Ok(serde_path_to_error::deserialize::<_, T>(json_deserializer)?)
}
#[cfg(feature = "sonic-rs")]
"json" => {
let json_deserializer = &mut sonic_rs::serde::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)?)
}
_ => {
drop(body);
Err(Error::UnsupportedMimeType {
mime_type: content_type.to_string(),
})
}
}
}
fn content_type(&self) -> Result<Mime> {
let header_str = self
.request_headers()
.get_str(ContentType)
.ok_or(Error::MissingContentType)?;
header_str.parse().map_err(|_| Error::UnsupportedMimeType {
mime_type: header_str.into(),
})
}
#[cfg(any(feature = "sonic-rs", feature = "serde_json"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "sonic-rs", feature = "serde_json"))))]
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?;
#[cfg(feature = "serde_json")]
let json_deserializer = &mut serde_json::Deserializer::from_str(&body);
#[cfg(feature = "sonic-rs")]
let json_deserializer = &mut sonic_rs::serde::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
.request_headers()
.get_str(Accept)
.unwrap_or("*/*")
.split(',')
.map(|s| s.trim())
.find_map(acceptable_mime_type);
match accept {
#[cfg(feature = "serde_json")]
Some(AcceptableMime::Json) => {
self.set_body(serde_json::to_string(body)?);
self.insert_response_header(ContentType, "application/json");
Ok(())
}
#[cfg(feature = "sonic-rs")]
Some(AcceptableMime::Json) => {
self.set_body(sonic_rs::to_string(body)?);
self.insert_response_header(ContentType, "application/json");
Ok(())
}
#[cfg(feature = "forms")]
Some(AcceptableMime::Form) => {
self.set_body(serde_urlencoded::to_string(body)?);
self.insert_response_header(ContentType, "application/x-www-form-urlencoded");
Ok(())
}
None => {
let _ = body;
Err(Error::FailureToNegotiateContent)
}
}
}
}
enum AcceptableMime {
#[cfg_attr(docsrs, doc(cfg(any(feature = "sonic-rs", feature = "serde_json"))))]
#[cfg(any(feature = "sonic-rs", feature = "serde_json"))]
Json,
#[cfg(feature = "forms")]
#[cfg_attr(docsrs, doc(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 {
#[cfg(any(feature = "serde_json", feature = "sonic-rs"))]
"*" | "json" => Some(AcceptableMime::Json),
#[cfg(feature = "forms")]
"x-www-form-urlencoded" => Some(AcceptableMime::Form),
_ => None,
}
}