-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.rs
More file actions
231 lines (200 loc) · 6.63 KB
/
client.rs
File metadata and controls
231 lines (200 loc) · 6.63 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
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use std::io::Read;
use reqwest::blocking::{Body, Client, Response};
use reqwest::header::{
ACCEPT, AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderMap, HeaderValue,
};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use super::error::ApiError;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletedPart {
pub part_number: u64,
pub etag: String,
}
const DEFAULT_BASE_URL: &str = "https://api.builtfast.com";
const USER_AGENT: &str = concat!("vector-cli/", env!("CARGO_PKG_VERSION"));
pub struct ApiClient {
client: Client,
base_url: String,
token: Option<String>,
}
impl ApiClient {
pub fn new(base_url: Option<String>, token: Option<String>) -> Result<Self, ApiError> {
let client = Client::builder()
.user_agent(USER_AGENT)
.build()
.map_err(ApiError::NetworkError)?;
Ok(Self {
client,
base_url: base_url.unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
token,
})
}
pub fn set_token(&mut self, token: String) {
self.token = Some(token);
}
fn headers(&self) -> Result<HeaderMap, ApiError> {
let mut headers = HeaderMap::new();
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
if let Some(ref token) = self.token {
let auth_value = format!("Bearer {}", token);
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&auth_value)
.map_err(|e| ApiError::ConfigError(e.to_string()))?,
);
}
Ok(headers)
}
fn handle_response<T: DeserializeOwned>(&self, response: Response) -> Result<T, ApiError> {
let status = response.status();
let body = response.text().map_err(ApiError::NetworkError)?;
if status.is_success() {
serde_json::from_str(&body)
.map_err(|e| ApiError::Other(format!("JSON parse error: {}", e)))
} else {
Err(ApiError::from_response(status.as_u16(), &body))
}
}
pub fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T, ApiError> {
let url = format!("{}{}", self.base_url, path);
let response = self
.client
.get(&url)
.headers(self.headers()?)
.send()
.map_err(ApiError::NetworkError)?;
self.handle_response(response)
}
pub fn get_with_query<T: DeserializeOwned, Q: Serialize>(
&self,
path: &str,
query: &Q,
) -> Result<T, ApiError> {
let url = format!("{}{}", self.base_url, path);
let response = self
.client
.get(&url)
.headers(self.headers()?)
.query(query)
.send()
.map_err(ApiError::NetworkError)?;
self.handle_response(response)
}
pub fn post<T: DeserializeOwned, B: Serialize>(
&self,
path: &str,
body: &B,
) -> Result<T, ApiError> {
let url = format!("{}{}", self.base_url, path);
let response = self
.client
.post(&url)
.headers(self.headers()?)
.json(body)
.send()
.map_err(ApiError::NetworkError)?;
self.handle_response(response)
}
pub fn post_empty<T: DeserializeOwned>(&self, path: &str) -> Result<T, ApiError> {
let url = format!("{}{}", self.base_url, path);
let response = self
.client
.post(&url)
.headers(self.headers()?)
.send()
.map_err(ApiError::NetworkError)?;
self.handle_response(response)
}
pub fn put<T: DeserializeOwned, B: Serialize>(
&self,
path: &str,
body: &B,
) -> Result<T, ApiError> {
let url = format!("{}{}", self.base_url, path);
let response = self
.client
.put(&url)
.headers(self.headers()?)
.json(body)
.send()
.map_err(ApiError::NetworkError)?;
self.handle_response(response)
}
pub fn put_empty<T: DeserializeOwned>(&self, path: &str) -> Result<T, ApiError> {
let url = format!("{}{}", self.base_url, path);
let response = self
.client
.put(&url)
.headers(self.headers()?)
.send()
.map_err(ApiError::NetworkError)?;
self.handle_response(response)
}
pub fn put_file(
&self,
url: &str,
file: std::fs::File,
content_length: u64,
) -> Result<(), ApiError> {
let response = self
.client
.put(url)
.header(CONTENT_TYPE, "application/gzip")
.header(CONTENT_LENGTH, content_length)
.body(Body::from(file))
.send()
.map_err(ApiError::NetworkError)?;
if response.status().is_success() {
Ok(())
} else {
let status = response.status();
let body = response.text().map_err(ApiError::NetworkError)?;
Err(ApiError::Other(format!(
"Upload failed ({}): {}",
status, body
)))
}
}
pub fn put_file_part<R: Read + Send + 'static>(
&self,
url: &str,
reader: R,
content_length: u64,
) -> Result<String, ApiError> {
let response = self
.client
.put(url)
.header(CONTENT_TYPE, "application/gzip")
.body(Body::sized(reader, content_length))
.send()
.map_err(ApiError::NetworkError)?;
if response.status().is_success() {
let etag = response
.headers()
.get("etag")
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string())
.ok_or_else(|| ApiError::Other("S3 response missing ETag header".to_string()))?;
Ok(etag)
} else {
let status = response.status();
let body = response.text().map_err(ApiError::NetworkError)?;
Err(ApiError::Other(format!(
"Part upload failed ({}): {}",
status, body
)))
}
}
pub fn delete<T: DeserializeOwned>(&self, path: &str) -> Result<T, ApiError> {
let url = format!("{}{}", self.base_url, path);
let response = self
.client
.delete(&url)
.headers(self.headers()?)
.send()
.map_err(ApiError::NetworkError)?;
self.handle_response(response)
}
}