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
use crate::error::Result;
use http;
pub(crate) type RawRequest = http::Request<Vec<u8>>;
pub(crate) type RawResponse = http::Response<Vec<u8>>;
pub(crate) mod sealed {
pub trait Sealed {}
}
#[must_use = "Api do nothing unless you `execute` them"]
pub trait Api: sealed::Sealed + Send + Sync + Sized {
type Response;
fn execute(self, client: &impl Client) -> Result<Self::Response>;
}
pub(crate) struct SimpleApi {
request: Result<RawRequest>,
}
impl sealed::Sealed for SimpleApi {}
impl Api for SimpleApi {
type Response = RawResponse;
fn execute(self, client: &impl Client) -> Result<Self::Response> {
client.execute_api(self.request?)
}
}
impl SimpleApi {
pub(crate) fn new(request: Result<RawRequest>) -> Self {
Self { request }
}
}
pub(crate) trait ApiExt: Api {
fn and_then<T, F>(self, f: F) -> AndThen<Self, F>
where
F: FnOnce(Self::Response) -> Result<T> + Send + Sync,
{
AndThen { api: self, f }
}
}
impl<A: Api> ApiExt for A {}
pub(crate) struct AndThen<A, F> {
api: A,
f: F,
}
impl<A, F> sealed::Sealed for AndThen<A, F> {}
impl<A: Api, T, F> Api for AndThen<A, F>
where
F: FnOnce(A::Response) -> Result<T> + Send + Sync,
{
type Response = T;
fn execute(self, client: &impl Client) -> Result<Self::Response> {
self.api.execute(client).and_then(self.f)
}
}
pub trait Client {
fn execute_api(&self, req: RawRequest) -> Result<RawResponse>;
}
#[cfg(feature = "reqwest")]
fn to_reqwest_request(req: RawRequest) -> ::reqwest::Request {
let (parts, body) = req.into_parts();
let url = ::reqwest::Url::parse(&parts.uri.to_string()).unwrap();
let mut req = ::reqwest::Request::new(parts.method, url);
*req.headers_mut() = parts.headers;
*req.body_mut() = Some(body.into());
req
}
#[cfg(feature = "reqwest")]
fn from_reqwest_response(mut resp: ::reqwest::Response) -> Result<RawResponse> {
let mut b = http::Response::builder();
b.headers_mut().unwrap().clone_from(resp.headers());
let mut buf = vec![];
resp.copy_to(&mut buf)?;
Ok(b.status(resp.status()).body(buf)?)
}
#[cfg(feature = "reqwest")]
impl Client for ::reqwest::Client {
fn execute_api(&self, req: RawRequest) -> Result<RawResponse> {
let req = to_reqwest_request(req);
let resp = self.execute(req)?;
from_reqwest_response(resp)
}
}