-
Notifications
You must be signed in to change notification settings - Fork 42
/
response.rs
176 lines (158 loc) · 4.91 KB
/
response.rs
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
use http::StatusCode;
use serde_json::Value;
use crate::ServerError;
use super::Error;
#[derive(PartialEq, Debug)]
#[allow(clippy::module_name_repetitions)] // Honestly clippy, get fucked
pub struct UpstreamResponse {
pub data: serde_json::Value,
pub errors: Vec<ServerError>,
}
impl UpstreamResponse {
pub fn from_response_text(
http_status: StatusCode,
response_text_result: Result<String, impl Into<Error>>,
) -> Result<Self, Error> {
let response_text = response_text_result
.map_err(|error| handle_error_after_response(http_status, error, None))?;
serde_json::from_str::<UpstreamResponse>(&response_text)
.map_err(|error| handle_error_after_response(http_status, error, Some(response_text)))
}
}
impl<'de> serde::Deserialize<'de> for UpstreamResponse {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
#[derive(serde::Deserialize)]
struct ResponseDeser {
/// The operation data (if the operation was successful)
data: Option<Value>,
/// Any errors that occurred as part of this operation
errors: Option<Vec<ServerError>>,
}
let ResponseDeser { data, errors } = ResponseDeser::deserialize(deserializer)?;
if data.is_none() && errors.is_none() {
return Err(D::Error::custom(
"neither data or errors were present in the upstream response",
));
}
Ok(UpstreamResponse {
data: data.unwrap_or(Value::Null),
errors: errors.unwrap_or_default(),
})
}
}
/// If we encountered an error handling a GraphQL response then we want to log the
/// body for debugging purposes. But we also want to check the HTTP status code
/// and use that as our primary error if it's not success.
fn handle_error_after_response(
status: StatusCode,
error: impl Into<Error>,
#[allow(unused)] response_body: Option<String>,
) -> Error {
let error = error.into();
#[cfg(feature = "tracing_worker")]
{
logworker::debug!("", "Error in GraphQL connector: {error}");
if let Some(text) = response_body {
logworker::debug!("", "Response Body: {text}");
}
}
if !status.is_success() {
return Error::HttpErrorResponse(status.as_u16());
}
error
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use serde_json::json;
use super::*;
#[rstest]
#[case(200, r#"{"data": {}}"#, UpstreamResponse {
data: json!({}),
errors: vec![]
})]
#[case(200, r#"{"errors": []}"#, UpstreamResponse {
data: json!(null),
errors: vec![]
})]
#[case(200, r#"
{"errors": [{
"message": "oh no"
}]}
"#, UpstreamResponse {
data: json!(null),
errors: vec![ServerError {
message: "oh no".into(),
source: None,
locations: vec![],
path: vec![],
extensions: None
}]
})]
#[case(500, r#"
{"errors": [{
"message": "oh no"
}]}
"#, UpstreamResponse {
data: json!(null),
errors: vec![ServerError {
message: "oh no".into(),
source: None,
locations: vec![],
path: vec![],
extensions: None
}]
})]
#[case(200, r#"{"data": {}}"#, UpstreamResponse {
data: json!({}),
errors: vec![]
})]
fn test_happy_paths(
#[case] status_code: u16,
#[case] text: &str,
#[case] expected_response: UpstreamResponse,
) {
assert_eq!(
UpstreamResponse::from_response_text(
StatusCode::from_u16(status_code).unwrap(),
Ok::<_, Error>(text.to_string())
)
.unwrap(),
expected_response
);
}
#[test]
fn test_error_paths() {
let response = UpstreamResponse::from_response_text(
StatusCode::from_u16(500).unwrap(),
Ok::<_, Error>(r#"{"blah": {}}"#.into()),
)
.unwrap_err();
assert!(
matches!(response, Error::HttpErrorResponse(500)),
"`{response}` does not match"
);
let response = UpstreamResponse::from_response_text(
StatusCode::from_u16(200).unwrap(),
Ok::<_, Error>(r#"{"blah": {}}"#.into()),
)
.unwrap_err();
assert!(
matches!(response, Error::JsonDecodeError(_)),
"{response} does not match"
);
let response = UpstreamResponse::from_response_text(
StatusCode::from_u16(200).unwrap(),
Ok::<_, Error>(r#"{"errors": "bad"}"#.into()),
)
.unwrap_err();
assert!(
matches!(response, Error::JsonDecodeError(_)),
"{response} does not match"
);
}
}