Skip to main content

financial_api/client/
response.rs

1use serde::de::DeserializeOwned;
2
3use super::Response;
4use crate::error::{BusinessError, Error};
5
6impl<T> Response<T> {
7    /// 上游请求追踪标识。
8    #[must_use]
9    pub fn request_id(&self) -> &str {
10        &self.request_id
11    }
12
13    /// 端点特定的响应数据。
14    #[must_use]
15    pub const fn data(&self) -> &T {
16        &self.data
17    }
18
19    /// 消耗响应并返回端点数据。
20    #[must_use]
21    pub fn into_data(self) -> T {
22        self.data
23    }
24}
25
26impl Response<serde_json::Value> {
27    /// 将无损 JSON 数据解码为应用自有的响应类型。
28    pub fn into_typed<T: DeserializeOwned>(self) -> Result<Response<T>, Error> {
29        let data = serde_json::from_value(self.data).map_err(|source| Error::InvalidResponse {
30            source: Some(source),
31        })?;
32        Ok(Response {
33            request_id: self.request_id,
34            data,
35        })
36    }
37}
38
39pub(super) fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<Response<T>, Error> {
40    let envelope: Envelope =
41        serde_json::from_slice(bytes).map_err(|source| Error::InvalidResponse {
42            source: Some(source),
43        })?;
44
45    if envelope.code != 0 {
46        return Err(
47            BusinessError::new(envelope.code, envelope.message, envelope.request_id).into(),
48        );
49    }
50
51    let data = serde_json::from_value(envelope.data).map_err(|source| Error::InvalidResponse {
52        source: Some(source),
53    })?;
54    Ok(Response {
55        request_id: envelope.request_id,
56        data,
57    })
58}
59
60#[derive(serde::Deserialize)]
61struct Envelope {
62    code: i64,
63    message: String,
64    request_id: String,
65    data: serde_json::Value,
66}
67
68#[cfg(test)]
69mod tests {
70    use serde_json::{Value, json};
71
72    use super::decode;
73    use crate::Error;
74
75    fn assert_invalid_response(body: Value) {
76        let bytes = serde_json::to_vec(&body).unwrap();
77        assert!(matches!(
78            decode::<Value>(&bytes).unwrap_err(),
79            Error::InvalidResponse { .. }
80        ));
81    }
82
83    #[test]
84    fn business_errors_require_the_complete_common_envelope() {
85        for body in [
86            json!({
87                "code": 2003,
88                "message": "request rejected",
89                "request_id": "request-1"
90            }),
91            json!({
92                "code": 2003,
93                "message": "request rejected",
94                "data": null
95            }),
96            json!({
97                "code": 2003,
98                "request_id": "request-3",
99                "data": null
100            }),
101        ] {
102            assert_invalid_response(body);
103        }
104    }
105
106    #[test]
107    fn malformed_success_response_is_an_invalid_response() {
108        assert!(matches!(
109            decode::<Value>(b"not-json").unwrap_err(),
110            Error::InvalidResponse { .. }
111        ));
112    }
113
114    #[test]
115    fn successful_envelope_requires_trace_and_data_fields() {
116        for body in [
117            json!({"code": 0, "message": "success", "data": {}}),
118            json!({"code": 0, "message": "success", "request_id": "request"}),
119            json!({"code": 0, "request_id": "request", "data": {}}),
120        ] {
121            assert_invalid_response(body);
122        }
123    }
124}