apisdk 0.0.1

A highlevel API client framework for Rust.
Documentation
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use std::collections::HashMap;

use serde::{de::DeserializeOwned, Deserialize};
use serde_json::Value;

use crate::{ApiError, ApiResult};

/// This trait is used to extract result from response.
///
/// # Usage
///
/// ```
/// let req = client.get("/api/path").await?;
/// let res = send!(req, TypeOfJsonExtractor).await?;
/// ```
///
/// # Examples
///
/// ### Check return code
///
/// ```
/// pub struct CheckReturnCode;
///
/// impl JsonExtractor for CheckReturnCode {
///     fn try_extract<T>(value: Value) -> ApiResult<T> {
///         match value.get("ret_code").and_then(|c| c.as_i64()) {
///             Some(0) => serde_json::from_value(value).map_err(|e| e.into()),
///             Some(c) => Err(ApiError::BusinessError(c, Some("Invalid ret_code"))),
///             None => Err(ApiError::BusinessError(c, Some("No ret_code"))),
///         }
///     }
/// }
/// ```
///
/// ### Extract single field
///
/// ```
/// pub struct ExtractData;
///
/// impl JsonExtractor for ExtractData {
///     fn try_extract<T>(value: Value) -> ApiResult<T> {
///         let data = value.get("data").unwrap_or(Value::Null);
///         serde_json::from_value(data).map_err(|e| e.into())
///     }
/// }
/// ```
///
/// # Built-in Extractors
///
/// - serde_json::Value
///     - treat whole payload as output
/// - apisdk::WholePayload
///     - an alias of serde_json::Value
/// - apisdk::CodeDataMessage
///     - parse `{code, data, message}` payload, and return `data` field
pub trait JsonExtractor {
    /// The extractor needs response HTTP headers or not.
    fn require_headers() -> bool {
        false
    }

    /// Try to extract result from response.
    ///
    /// The HTTP headers will be inject as `__headers__` field if possible.
    /// - value: the response payload
    fn try_extract<T>(value: Value) -> ApiResult<T>
    where
        T: DeserializeOwned;
}

impl JsonExtractor for Value {
    fn try_extract<T>(value: Value) -> ApiResult<T>
    where
        T: DeserializeOwned,
    {
        serde_json::from_value(value).map_err(|e| e.into())
    }
}

/// This extractor will treat whole payload as result
pub type WholePayload = Value;

/// This struct is used to parse `{code, data, message}` payload.
///
/// When it's used as `JsonExtractor`, it will extract `data` from payload.
///
/// # Examples
///
/// ### As JsonExtractor
///
/// To be used as `JsonExtractor`, `CodeDataMessage` will check `code` field of response payload, and ensure it must be `0`.
/// If not, it will generate an ApiError instance with `code` and `message`.
///
/// ```
/// async fn get_user(&self) -> ApiResult<User> {
///     let req = client.get("/api/path").await?;
///     send!(req, CodeDataMessage).await
/// }
/// ```
///
/// ### As Result
///
/// If we want to access the response headers or extra fields, we could use `CodeDataMessage` as result type.
///
/// ```
/// async fn get_user(&self) -> ApiResult<User> {
///     let req = client.get("/api/path").await?;
///     let res: CodeDataMessage<User> = send!(req).await?;
///     // to access HTTP headers: res.get_header("name")
///     // to access extra fields: res.get_extra("other_field")
///     if res.is_success() {
///         Ok(res.data)
///     } else {
///         Err(ApiError::BusinessError(res.code, res.get_header().map(|v| v.to_string())))
///     }
/// }
/// ```
#[derive(Debug, Deserialize)]
pub struct CodeDataMessage<T = Option<Value>> {
    /// `code` field
    pub code: i64,
    /// `data` field
    pub data: T,
    /// `message` or `msg` field
    #[serde(alias = "msg")]
    pub message: Option<String>,
    /// Hold all HTTP headers
    #[serde(rename = "__headers__", default)]
    headers: HashMap<String, String>,
    /// Hold unknown fields
    #[serde(flatten)]
    extra: HashMap<String, Value>,
}

impl<T> CodeDataMessage<T> {
    /// Check whether `code` is 0
    pub fn is_success(&self) -> bool {
        self.code == 0
    }

    /// Get any header
    /// - name: header name
    pub fn get_header(&self, name: &str) -> Option<&str> {
        self.headers.get(name).map(|v| v.as_str())
    }

    /// Get any unknown field
    /// - name: field name
    pub fn get_extra<D>(&self, name: &str) -> Option<D>
    where
        D: DeserializeOwned,
    {
        self.extra
            .get(name)
            .and_then(|v| serde_json::from_value(v.clone()).ok())
    }

    /// Get `X-Request-ID` header
    pub fn get_request_id(&self) -> Option<&str> {
        self.get_header("X-Request-ID")
    }

    /// Get `X-Trace-ID` header
    pub fn get_trace_id(&self) -> Option<&str> {
        self.get_header("X-Trace-ID")
    }

    /// Get `X-Span-ID` header
    pub fn get_span_id(&self) -> Option<&str> {
        self.get_header("X-Span-ID")
    }
}

impl JsonExtractor for CodeDataMessage {
    fn try_extract<T>(value: Value) -> ApiResult<T>
    where
        T: DeserializeOwned,
    {
        let mut value = value;
        match value.get("code").and_then(|c| c.as_i64()) {
            // Extract `data` field when `code` is 0
            Some(0) => match value.get_mut("data") {
                Some(data) => serde_json::from_value(data.take()).map_err(|e| e.into()),
                None => serde_json::from_value(Value::Null).map_err(|e| e.into()),
            },
            // Build error when `code` is not 0
            Some(code) => {
                let message = value
                    .get("message")
                    .or_else(|| value.get("msg"))
                    .and_then(|m| m.as_str())
                    .map(|m| m.to_string());
                Err(ApiError::BusinessError(code, message))
            }
            // Failed to parse without `code` field
            None => Err(ApiError::InvalidJson(value)),
        }
    }
}

#[cfg(test)]
mod tests {
    use serde::Deserialize;
    use serde_json::Value;

    use super::CodeDataMessage;

    #[derive(Debug, Deserialize)]
    #[allow(unused)]
    struct Payload {
        pub key: u32,
    }

    #[test]
    fn test_parse_null() {
        let v: Value = serde_json::from_str("null").unwrap();
        println!("v = {:?}", v);

        let v: Value = serde_json::from_value(Value::Null).unwrap();
        println!("v = {:?}", v);

        let v: Option<Value> = serde_json::from_str("null").unwrap();
        println!("v = {:?}", v);

        let v: Option<Value> = serde_json::from_value(Value::Null).unwrap();
        println!("v = {:?}", v);
    }

    #[test]
    fn test_cdm_data_miss_2_option_value() {
        let cdm: CodeDataMessage<Option<Value>> = serde_json::from_str(
            r#"
            {
                "code": 0
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_miss_2_option_value = {:?}", cdm);
    }

    #[test]
    fn test_cdm_data_null_2_option_value() {
        let cdm: CodeDataMessage<Option<Value>> = serde_json::from_str(
            r#"
            {
                "code": 0,
                "data": null
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_null_2_option_value = {:?}", cdm);
    }

    #[test]
    fn test_cdm_data_json_2_option_value() {
        let cdm: CodeDataMessage<Option<Value>> = serde_json::from_str(
            r#"
            {
                "code": 0,
                "data": {
                    "key": 1
                }
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_json_2_option_value = {:?}", cdm);
    }

    #[test]
    #[should_panic]
    fn test_cdm_data_miss_2_value() {
        let cdm: CodeDataMessage<Value> = serde_json::from_str(
            r#"
            {
                "code": 0
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_miss_2_value = {:?}", cdm);
    }

    #[test]
    fn test_cdm_data_null_2_value() {
        let cdm: CodeDataMessage<Value> = serde_json::from_str(
            r#"
            {
                "code": 0,
                "data": null
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_null_2_value = {:?}", cdm);
    }

    #[test]
    fn test_cdm_data_json_2_value() {
        let cdm: CodeDataMessage<Value> = serde_json::from_str(
            r#"
            {
                "code": 0,
                "data": {
                    "key": 1
                }
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_json_2_value = {:?}", cdm);
    }

    #[test]
    fn test_cdm_data_miss_2_option_payload() {
        let cdm: CodeDataMessage<Option<Payload>> = serde_json::from_str(
            r#"
            {
                "code": 0
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_miss_2_option_payload = {:?}", cdm);
    }

    #[test]
    fn test_cdm_data_null_2_option_payload() {
        let cdm: CodeDataMessage<Option<Payload>> = serde_json::from_str(
            r#"
            {
                "code": 0,
                "data": null
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_null_2_option_payload = {:?}", cdm);
    }

    #[test]
    fn test_cdm_data_json_2_option_payload() {
        let cdm: CodeDataMessage<Option<Payload>> = serde_json::from_str(
            r#"
            {
                "code": 0,
                "data": {
                    "key": 1
                }
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_json_2_option_payload = {:?}", cdm);
    }

    #[test]
    #[should_panic]
    fn test_cdm_data_miss_2_payload() {
        let cdm: CodeDataMessage<Payload> = serde_json::from_str(
            r#"
            {
                "code": 0
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_miss_2_payload = {:?}", cdm);
    }

    #[test]
    #[should_panic]
    fn test_cdm_data_null_2_payload() {
        let cdm: CodeDataMessage<Payload> = serde_json::from_str(
            r#"
            {
                "code": 0,
                "data": null
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_null_2_payload = {:?}", cdm);
    }

    #[test]
    fn test_cdm_data_json_2_payload() {
        let cdm: CodeDataMessage<Payload> = serde_json::from_str(
            r#"
            {
                "code": 0,
                "data": {
                    "key": 1
                }
            }
            "#,
        )
        .unwrap();
        println!("test_cdm_data_json_2_payload = {:?}", cdm);
    }

    #[test]
    fn test_cdm_extra() {
        let cdm: CodeDataMessage = serde_json::from_str(
            r#"
            {
                "code": 0,
                "num": 1,
                "text": "string"
            }
            "#,
        )
        .unwrap();
        println!("{:?}", cdm);
        println!("extra.num = {:?}", cdm.get_extra::<u32>("num"));
        println!("extra.text = {:?}", cdm.get_extra::<String>("text"));
    }
}