Skip to main content

financial_api/client/
response.rs

1use serde::de::DeserializeOwned;
2
3use super::Response;
4use crate::error::{BusinessError, Error};
5
6#[cfg(test)]
7mod tests;
8
9impl<T> Response<T> {
10    /// Upstream trace identifier.
11    #[must_use]
12    pub fn request_id(&self) -> &str {
13        &self.request_id
14    }
15
16    /// Endpoint-specific response data.
17    #[must_use]
18    pub const fn data(&self) -> &T {
19        &self.data
20    }
21
22    /// Consume the response and return its endpoint data.
23    #[must_use]
24    pub fn into_data(self) -> T {
25        self.data
26    }
27}
28
29impl Response<serde_json::Value> {
30    /// Decode lossless JSON data into an application-owned response type.
31    pub fn into_typed<T: DeserializeOwned>(self) -> Result<Response<T>, Error> {
32        let data = serde_json::from_value(self.data).map_err(|source| Error::InvalidResponse {
33            source: Some(source),
34        })?;
35        Ok(Response {
36            request_id: self.request_id,
37            data,
38        })
39    }
40}
41
42pub(super) fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<Response<T>, Error> {
43    let envelope: Envelope =
44        serde_json::from_slice(bytes).map_err(|source| Error::InvalidResponse {
45            source: Some(source),
46        })?;
47
48    if envelope.code != 0 {
49        return Err(
50            BusinessError::new(envelope.code, envelope.message, envelope.request_id).into(),
51        );
52    }
53
54    let data = serde_json::from_value(envelope.data).map_err(|source| Error::InvalidResponse {
55        source: Some(source),
56    })?;
57    Ok(Response {
58        request_id: envelope.request_id,
59        data,
60    })
61}
62
63#[derive(serde::Deserialize)]
64struct Envelope {
65    code: i64,
66    message: String,
67    request_id: String,
68    data: serde_json::Value,
69}