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)
30            .map_err(|source| Error::InvalidResponse { source })?;
31        Ok(Response {
32            request_id: self.request_id,
33            data,
34        })
35    }
36}
37
38pub(super) fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<Response<T>, Error> {
39    let envelope: Envelope =
40        serde_json::from_slice(bytes).map_err(|source| Error::InvalidResponse { source })?;
41
42    if envelope.code != 0 {
43        return Err(
44            BusinessError::new(envelope.code, envelope.message, envelope.request_id).into(),
45        );
46    }
47
48    let data = serde_json::from_value(envelope.data)
49        .map_err(|source| Error::InvalidResponse { source })?;
50    Ok(Response {
51        request_id: envelope.request_id,
52        data,
53    })
54}
55
56#[derive(serde::Deserialize)]
57struct Envelope {
58    code: i64,
59    message: String,
60    request_id: String,
61    data: serde_json::Value,
62}
63
64#[cfg(test)]
65mod tests {
66    use serde_json::{Value, json};
67
68    use super::decode;
69    use crate::Error;
70
71    fn assert_invalid_response(body: Value) {
72        let bytes = serde_json::to_vec(&body).unwrap();
73        assert!(matches!(
74            decode::<Value>(&bytes).unwrap_err(),
75            Error::InvalidResponse { .. }
76        ));
77    }
78
79    #[test]
80    fn business_errors_require_the_complete_common_envelope() {
81        for body in [
82            json!({
83                "code": 2003,
84                "message": "request rejected",
85                "request_id": "request-1"
86            }),
87            json!({
88                "code": 2003,
89                "message": "request rejected",
90                "data": null
91            }),
92            json!({
93                "code": 2003,
94                "request_id": "request-3",
95                "data": null
96            }),
97        ] {
98            assert_invalid_response(body);
99        }
100    }
101
102    #[test]
103    fn malformed_success_response_is_an_invalid_response() {
104        assert!(matches!(
105            decode::<Value>(b"not-json").unwrap_err(),
106            Error::InvalidResponse { .. }
107        ));
108    }
109
110    #[test]
111    fn successful_envelope_requires_trace_and_data_fields() {
112        for body in [
113            json!({"code": 0, "message": "success", "data": {}}),
114            json!({"code": 0, "message": "success", "request_id": "request"}),
115            json!({"code": 0, "request_id": "request", "data": {}}),
116        ] {
117            assert_invalid_response(body);
118        }
119    }
120}