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
use async_trait::async_trait;
use serde::Deserialize;
#[async_trait]
pub trait InspectJson<C>
where
C: FnOnce(&str) + Send + 'static
{
async fn inspect_json<T, E>(self, callback: C) -> Result<T, E>
where
T: for<'de> Deserialize<'de>,
E: From<reqwest::Error>,
E: From<serde_json::Error>;
}
#[async_trait]
impl<C> InspectJson<C> for reqwest::Response
where
C: FnOnce(&str) + Send + 'static
{
async fn inspect_json<T, E>(self, callback: C) -> Result<T, E>
where
T: for<'de> Deserialize<'de>,
E: From<reqwest::Error>,
E: From<serde_json::Error>
{
let full = self
.text()
.await?;
callback(&full);
let json = serde_json::from_str(&full)?;
Ok(json)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::{Deserialize, Serialize};
use std::error::Error;
#[derive(Debug)]
enum DebugError {
Reqwest(reqwest::Error),
ParseError(serde_json::Error),
}
impl std::fmt::Display for DebugError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:#?}", self)
}
}
impl From<reqwest::Error> for DebugError{
fn from(err: reqwest::Error) -> Self {
DebugError::Reqwest(err)
}
}
impl From<serde_json::Error> for DebugError{
fn from(err: serde_json::Error) -> Self {
DebugError::ParseError(err)
}
}
impl std::error::Error for DebugError {
}
#[tokio::test]
async fn debug_json_async_test() -> Result<(), Box<dyn Error>> {
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
struct TestDataClass {
key1: String,
key2: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct Response {
json: TestDataClass,
}
let test_data = TestDataClass {
key1: "asdada".to_owned(),
key2: "asdagfdgdf".to_owned(),
};
let test_data_copy = test_data.clone();
let client = reqwest::Client::new();
let response = client
.post("http://httpbin.org/post")
.json(&test_data)
.send()
.await
.expect("Request failed")
.inspect_json::<Response, DebugError>(move |text| {
let text_data = serde_json::from_str::<Response>(text).expect("Parsing failed");
assert_eq!(text_data.json, test_data_copy);
})
.await
.expect("Response parse failed");
assert_eq!(response.json, test_data);
Ok(())
}
}