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
//! Contains all data types for error handling

use serde::Deserialize;

/// API common HTTP response scheme
#[derive(Clone, Debug, Eq, PartialEq, Default, Deserialize)]
pub struct ApiResponse {
    /// The response status
    #[serde(rename = "status", skip_serializing_if = "Option::is_none")]
    pub status: Option<ApiStatus>,
    /// The error message
    #[serde(rename = "message", skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// More information about the error. This field may be empty depending on error type
    #[serde(rename = "data", skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

/// Status returned from the API
#[derive(Deserialize, PartialEq, Eq, Debug, Clone)]
#[serde(rename_all = "lowercase")]
pub enum ApiStatus {
    /// The request was a Success
    Success,
    /// There was an Error while processing the request
    Error,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn given_good_response_when_deserializing_status_then_return_struct() {
        let string = r#"{ "status": "success", "data": { "test1": 42 } }"#;

        let status: ApiResponse = serde_json::from_str(string).expect("Error with deserialization");

        assert_eq!(
            status,
            ApiResponse {
                status: Some(ApiStatus::Success),
                message: None,
                data: Some(json!({"test1": 42}))
            }
        );
    }

    #[test]
    fn given_error_repsonse_when_deserializing_status_then_return_struct() {
        let string =
            r#"{ "status": "error", "message": "testing message", "data": { "test1": 42 } }"#;

        let status: ApiResponse = serde_json::from_str(string).expect("Error with deserialization");

        assert_eq!(
            status,
            ApiResponse {
                status: Some(ApiStatus::Error),
                message: Some("testing message".into()),
                data: Some(json!({"test1": 42}))
            }
        );
    }

    #[test]
    #[should_panic]
    fn given_any_repsonse_when_deserializing_status_then_return_struct() {
        let string = r#"{ "status": "any", "data": { }"#;

        let status: ApiResponse = serde_json::from_str(string).expect("Error with deserialization");

        assert_eq!(
            status,
            ApiResponse {
                status: Some(ApiStatus::Error),
                message: None,
                data: Some(json!({}))
            }
        );
    }
}