-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathrequest.rs
More file actions
70 lines (63 loc) · 2.25 KB
/
Copy pathrequest.rs
File metadata and controls
70 lines (63 loc) · 2.25 KB
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
use http::header::CONTENT_TYPE;
use serde::de::{DeserializeOwned, Error as _};
use crate::{ContentType, Error, ResponseContent};
fn content_type(response: &reqwest::Response) -> ContentType {
response
.headers()
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream")
.into()
}
/// [process_with_json_response] is generic, which means it gets monomorphized for every type it's
/// used with. This function contains the non-generic logic for processing the response so that it
/// doesn't get duplicated.
#[inline(never)]
async fn process_with_json_response_internal(
request: reqwest_middleware::RequestBuilder,
) -> Result<String, crate::Error> {
let response = request.send().await?;
let status = response.status();
let content_type = content_type(&response);
let content = response.text().await?;
if !status.is_client_error() && !status.is_server_error() {
match content_type {
ContentType::Json => Ok(content),
ct => Err(Error::from(serde_json::Error::custom(format!(
"Received `{ct:?}` content type response when JSON was expected"
)))),
}
} else {
Err(ResponseContent {
status,
message: content,
}
.into())
}
}
/// Sends and processes a request expecting a JSON response, deserializing it into the type `T`.
pub async fn process_with_json_response<T: DeserializeOwned>(
request: reqwest_middleware::RequestBuilder,
) -> Result<T, crate::Error> {
process_with_json_response_internal(request)
.await
.and_then(|content| serde_json::from_str(&content).map_err(Into::into))
}
/// Sends and processes a request expecting an empty response, returning `Ok(())` when successful.
#[inline(never)]
pub async fn process_with_empty_response(
request: reqwest_middleware::RequestBuilder,
) -> Result<(), crate::Error> {
let response = request.send().await?;
let status = response.status();
if !status.is_client_error() && !status.is_server_error() {
Ok(())
} else {
let content = response.text().await?;
Err(ResponseContent {
status,
message: content,
}
.into())
}
}