Skip to main content

riven/
response_info.rs

1use reqwest::Response;
2
3use crate::{Result, RiotApiError};
4
5/// A "raw" unparsed successful response from the Riot API, for internal or advanced use cases.
6#[non_exhaustive]
7pub struct ResponseInfo {
8    /// The reqwest response.
9    pub response: Response,
10    /// The number of retries used, zero for first-try success.
11    pub retries: u8,
12    /// If the response has an HTTP status code indicating a `None` response (i.e. 204, 404).
13    pub status_none: bool,
14    /// Any reqwest errors that occurred. A response may still be successful even if this is non-empty due to retrying.
15    pub reqwest_errors: Vec<reqwest::Error>,
16}
17
18impl ResponseInfo {
19    /// Helper to deserialize the JSON-encoded value from a `ResponseInfo`, properly handling errors.
20    pub(crate) async fn json<T: for<'de> crate::de::Deserialize<'de>>(self) -> Result<T> {
21        let Self {
22            response,
23            retries,
24            status_none: _,
25            mut reqwest_errors,
26        } = self;
27        let status = response.status();
28        let bytes = match response.bytes().await {
29            Ok(bytes) => bytes,
30            Err(err) => {
31                reqwest_errors.push(err);
32                return Err(RiotApiError::new(
33                    reqwest_errors,
34                    None,
35                    retries,
36                    None, // `.bytes()` consumes the response.
37                    Some(status),
38                ));
39            }
40        };
41        let value = match crate::de::from_slice::<T>(&bytes) {
42            Ok(value) => value,
43            Err(serde_err) => {
44                return Err(RiotApiError::new(
45                    reqwest_errors,
46                    Some(serde_err),
47                    retries,
48                    None, // `.bytes()` consumes the response.
49                    Some(status),
50                ));
51            }
52        };
53        Ok(value)
54    }
55}