BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / src / request.rs

request.rs

eba4ad94 History
request.rs 6.7 KiB Download Raw
1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Method {
6 Get,
7 Post,
8 Put,
9 Patch,
10 Delete,
11}
12
13impl Method {
14 pub fn as_str(self) -> &'static str {
15 match self {
16 Method::Get => "GET",
17 Method::Post => "POST",
18 Method::Put => "PUT",
19 Method::Patch => "PATCH",
20 Method::Delete => "DELETE",
21 }
22 }
23}
24
25#[derive(Debug, Clone)]
26pub struct Request {
27 pub method: Method,
28 pub url: String,
29 pub headers: Vec<(String, String)>,
30 pub body: Option<Value>,
31 pub binary: bool,
32 pub anonymous: bool,
33 pub body_base64: Option<String>,
34}
35
36impl Request {
37 /// A successful answer carries `{"base64": .., "contentType": ..}` as its body.
38 pub fn binary_get(url: impl Into<String>) -> Self {
39 Request {
40 binary: true,
41 ..Request::get(url)
42 }
43 }
44
45 pub fn get(url: impl Into<String>) -> Self {
46 Request {
47 method: Method::Get,
48 url: url.into(),
49 headers: Vec::new(),
50 body: None,
51 binary: false,
52 anonymous: false,
53 body_base64: None,
54 }
55 }
56
57 /// Sent without an Authorization header, for pre-authenticated URLs such as upload sessions.
58 pub fn anonymous_bytes(method: Method, url: impl Into<String>, headers: Vec<(String, String)>, body_base64: String) -> Self {
59 Request {
60 method,
61 headers,
62 anonymous: true,
63 body_base64: Some(body_base64),
64 ..Request::get(url)
65 }
66 }
67
68 pub fn delete(url: impl Into<String>) -> Self {
69 Request {
70 method: Method::Delete,
71 ..Request::get(url)
72 }
73 }
74
75 pub fn with_body(method: Method, url: impl Into<String>, body: Value) -> Self {
76 Request {
77 method,
78 url: url.into(),
79 headers: Vec::new(),
80 body: Some(body),
81 binary: false,
82 anonymous: false,
83 body_base64: None,
84 }
85 }
86}
87
88#[derive(Debug, Clone)]
89pub struct ApiResponse {
90 pub status: u16,
91 pub body: Value,
92 pub retry_after: Option<String>,
93}
94
95impl ApiResponse {
96 pub fn is_success(&self) -> bool {
97 (200..400).contains(&self.status)
98 }
99}
100
101#[derive(Debug, Serialize)]
102pub(crate) struct WireRequest<'a> {
103 pub method: &'static str,
104 pub url: &'a str,
105 pub headers: serde_json::Map<String, Value>,
106 pub body: Option<String>,
107 #[serde(rename = "bodyBase64")]
108 pub body_base64: Option<&'a str>,
109 pub binary: bool,
110 pub anonymous: bool,
111}
112
113impl<'a> From<&'a Request> for WireRequest<'a> {
114 fn from(request: &'a Request) -> Self {
115 let mut headers: serde_json::Map<String, Value> = request
116 .headers
117 .iter()
118 .map(|(name, value)| (name.clone(), Value::String(value.clone())))
119 .collect();
120 if request.body.is_some() && !headers.keys().any(|name| name.eq_ignore_ascii_case("content-type")) {
121 headers.insert("Content-Type".into(), "application/json".into());
122 }
123 WireRequest {
124 method: request.method.as_str(),
125 url: &request.url,
126 headers,
127 body: request.body.as_ref().map(Value::to_string),
128 body_base64: request.body_base64.as_deref(),
129 binary: request.binary,
130 anonymous: request.anonymous,
131 }
132 }
133}
134
135#[derive(Debug, Deserialize)]
136pub(crate) struct WireResult {
137 pub status: u16,
138 #[serde(default)]
139 pub body: Value,
140 #[serde(default, rename = "retryAfter")]
141 pub retry_after: Option<String>,
142}
143
144#[derive(Debug, Deserialize)]
145pub(crate) struct Outcome {
146 pub results: Option<Vec<WireResult>>,
147 #[serde(default, rename = "refreshError")]
148 pub refresh_error: Option<String>,
149}
150
151impl From<WireResult> for ApiResponse {
152 fn from(wire: WireResult) -> Self {
153 ApiResponse {
154 status: wire.status,
155 body: wire.body,
156 retry_after: wire.retry_after,
157 }
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use serde_json::json;
164
165 use super::*;
166
167 #[test]
168 fn json_body_gets_content_type() {
169 let request = Request::with_body(Method::Post, "https://graph.microsoft.com/v1.0/x", json!({"a": 1}));
170 let wire = WireRequest::from(&request);
171 assert_eq!(wire.method, "POST");
172 assert_eq!(wire.body.as_deref(), Some(r#"{"a":1}"#));
173 assert_eq!(wire.headers["Content-Type"], "application/json");
174 }
175
176 #[test]
177 fn explicit_content_type_is_kept() {
178 let mut request = Request::with_body(Method::Post, "u", json!({}));
179 request.headers.push(("content-type".into(), "text/plain".into()));
180 let wire = WireRequest::from(&request);
181 assert_eq!(wire.headers.len(), 1);
182 }
183
184 #[test]
185 fn binary_get_is_flagged_on_the_wire() {
186 let request = Request::binary_get("u");
187 assert!(WireRequest::from(&request).binary);
188 assert!(!WireRequest::from(&Request::get("u")).binary);
189 }
190
191 #[test]
192 fn anonymous_bytes_travel_as_base64_without_a_content_type() {
193 let request = Request::anonymous_bytes(
194 Method::Put,
195 "https://upload.example/session",
196 vec![("Content-Range".into(), "bytes 0-2/3".into())],
197 "AQID".into(),
198 );
199 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
200 assert_eq!(wire["method"], "PUT");
201 assert_eq!(wire["anonymous"], true);
202 assert_eq!(wire["bodyBase64"], "AQID");
203 assert_eq!(wire["body"], Value::Null);
204 assert!(wire["headers"].get("Content-Type").is_none());
205 assert_eq!(wire["headers"]["Content-Range"], "bytes 0-2/3");
206 }
207
208 #[test]
209 fn get_has_no_body() {
210 let request = Request::get("u");
211 let wire = WireRequest::from(&request);
212 assert!(wire.body.is_none() && wire.headers.is_empty());
213 }
214
215 #[test]
216 fn parses_results_outcome() {
217 let outcome: Outcome = serde_json::from_value(json!({
218 "results": [{"status": 200, "retryAfter": null, "body": {"value": []}}, {"status": 429, "retryAfter": "4", "body": "slow"}]
219 }))
220 .unwrap();
221 let responses: Vec<ApiResponse> = outcome.results.unwrap().into_iter().map(Into::into).collect();
222 assert_eq!(responses[0].status, 200);
223 assert_eq!(responses[1].retry_after.as_deref(), Some("4"));
224 assert!(!responses[1].is_success());
225 }
226
227 #[test]
228 fn parses_no_token_outcome() {
229 let outcome: Outcome =
230 serde_json::from_value(json!({"noToken": true, "refreshError": "invalid_grant"})).unwrap();
231 assert!(outcome.results.is_none());
232 assert_eq!(outcome.refresh_error.as_deref(), Some("invalid_grant"));
233 }
234}