BlueGit

ict rusty-teams

Files

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

request.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
request.rs 5.3 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}
33
34impl Request {
35 /// A successful answer carries `{"base64": .., "contentType": ..}` as its body.
36 pub fn binary_get(url: impl Into<String>) -> Self {
37 Request {
38 binary: true,
39 ..Request::get(url)
40 }
41 }
42
43 pub fn get(url: impl Into<String>) -> Self {
44 Request {
45 method: Method::Get,
46 url: url.into(),
47 headers: Vec::new(),
48 body: None,
49 binary: false,
50 }
51 }
52
53 pub fn delete(url: impl Into<String>) -> Self {
54 Request {
55 method: Method::Delete,
56 ..Request::get(url)
57 }
58 }
59
60 pub fn with_body(method: Method, url: impl Into<String>, body: Value) -> Self {
61 Request {
62 method,
63 url: url.into(),
64 headers: Vec::new(),
65 body: Some(body),
66 binary: false,
67 }
68 }
69}
70
71#[derive(Debug, Clone)]
72pub struct ApiResponse {
73 pub status: u16,
74 pub body: Value,
75 pub retry_after: Option<String>,
76}
77
78impl ApiResponse {
79 pub fn is_success(&self) -> bool {
80 (200..400).contains(&self.status)
81 }
82}
83
84#[derive(Debug, Serialize)]
85pub(crate) struct WireRequest<'a> {
86 pub method: &'static str,
87 pub url: &'a str,
88 pub headers: serde_json::Map<String, Value>,
89 pub body: Option<String>,
90 pub binary: bool,
91}
92
93impl<'a> From<&'a Request> for WireRequest<'a> {
94 fn from(request: &'a Request) -> Self {
95 let mut headers: serde_json::Map<String, Value> = request
96 .headers
97 .iter()
98 .map(|(name, value)| (name.clone(), Value::String(value.clone())))
99 .collect();
100 if request.body.is_some() && !headers.keys().any(|name| name.eq_ignore_ascii_case("content-type")) {
101 headers.insert("Content-Type".into(), "application/json".into());
102 }
103 WireRequest {
104 method: request.method.as_str(),
105 url: &request.url,
106 headers,
107 body: request.body.as_ref().map(Value::to_string),
108 binary: request.binary,
109 }
110 }
111}
112
113#[derive(Debug, Deserialize)]
114pub(crate) struct WireResult {
115 pub status: u16,
116 #[serde(default)]
117 pub body: Value,
118 #[serde(default, rename = "retryAfter")]
119 pub retry_after: Option<String>,
120}
121
122#[derive(Debug, Deserialize)]
123pub(crate) struct Outcome {
124 pub results: Option<Vec<WireResult>>,
125 #[serde(default, rename = "refreshError")]
126 pub refresh_error: Option<String>,
127}
128
129impl From<WireResult> for ApiResponse {
130 fn from(wire: WireResult) -> Self {
131 ApiResponse {
132 status: wire.status,
133 body: wire.body,
134 retry_after: wire.retry_after,
135 }
136 }
137}
138
139#[cfg(test)]
140mod tests {
141 use serde_json::json;
142
143 use super::*;
144
145 #[test]
146 fn json_body_gets_content_type() {
147 let request = Request::with_body(Method::Post, "https://graph.microsoft.com/v1.0/x", json!({"a": 1}));
148 let wire = WireRequest::from(&request);
149 assert_eq!(wire.method, "POST");
150 assert_eq!(wire.body.as_deref(), Some(r#"{"a":1}"#));
151 assert_eq!(wire.headers["Content-Type"], "application/json");
152 }
153
154 #[test]
155 fn explicit_content_type_is_kept() {
156 let mut request = Request::with_body(Method::Post, "u", json!({}));
157 request.headers.push(("content-type".into(), "text/plain".into()));
158 let wire = WireRequest::from(&request);
159 assert_eq!(wire.headers.len(), 1);
160 }
161
162 #[test]
163 fn binary_get_is_flagged_on_the_wire() {
164 let request = Request::binary_get("u");
165 assert!(WireRequest::from(&request).binary);
166 assert!(!WireRequest::from(&Request::get("u")).binary);
167 }
168
169 #[test]
170 fn get_has_no_body() {
171 let request = Request::get("u");
172 let wire = WireRequest::from(&request);
173 assert!(wire.body.is_none() && wire.headers.is_empty());
174 }
175
176 #[test]
177 fn parses_results_outcome() {
178 let outcome: Outcome = serde_json::from_value(json!({
179 "results": [{"status": 200, "retryAfter": null, "body": {"value": []}}, {"status": 429, "retryAfter": "4", "body": "slow"}]
180 }))
181 .unwrap();
182 let responses: Vec<ApiResponse> = outcome.results.unwrap().into_iter().map(Into::into).collect();
183 assert_eq!(responses[0].status, 200);
184 assert_eq!(responses[1].retry_after.as_deref(), Some("4"));
185 assert!(!responses[1].is_success());
186 }
187
188 #[test]
189 fn parses_no_token_outcome() {
190 let outcome: Outcome =
191 serde_json::from_value(json!({"noToken": true, "refreshError": "invalid_grant"})).unwrap();
192 assert!(outcome.results.is_none());
193 assert_eq!(outcome.refresh_error.as_deref(), Some("invalid_grant"));
194 }
195}