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
#![warn(rust_2018_idioms)]
#![warn(clippy::pedantic)]
#![deny(warnings, missing_debug_implementations)]
#![doc(html_root_url = "https://docs.rs/reqwest-pretty-json/0.1.3")]
use reqwest::r#async::RequestBuilder as AsyncRequestBuilder;
use reqwest::RequestBuilder;
use serde::Serialize;
use serde_json::to_vec_pretty;
pub trait PrettyJson<T>: Sized
where
T: Serialize + ?Sized,
{
fn pretty_json(self, json: &T) -> Self;
}
impl<T> PrettyJson<T> for RequestBuilder
where
T: Serialize + ?Sized,
{
fn pretty_json(self, json: &T) -> Self {
let builder = self.json(json);
match to_vec_pretty(json) {
Ok(body) => builder.body(body),
Err(_) => builder,
}
}
}
impl<T> PrettyJson<T> for AsyncRequestBuilder
where
T: Serialize + ?Sized,
{
fn pretty_json(self, json: &T) -> Self {
let builder = self.json(json);
match to_vec_pretty(json) {
Ok(body) => builder.body(body),
Err(_) => builder,
}
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use reqwest::{Client, StatusCode};
use serde_json::{to_string, to_string_pretty, to_value, Value};
use super::*;
#[test]
fn add_pretty_json() {
let mut json_data = HashMap::new();
json_data.insert("foo", vec![1, 2, 3]);
let body_should_be = to_string_pretty(&json_data).unwrap();
let body_shouldnt_be = to_string(&json_data).unwrap();
let value = to_value(&json_data).unwrap();
let client = Client::new();
let mut response = client
.post("http://httpbin.org/post")
.pretty_json(&json_data)
.send()
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let result: Value = response.json().unwrap();
assert_eq!(result["data"], body_should_be);
assert_ne!(result["data"], body_shouldnt_be);
assert_eq!(result["headers"]["Content-Type"], "application/json");
assert_eq!(result["json"], value);
}
}