Skip to main content

bwx/
json.rs

1use crate::prelude::*;
2
3pub trait DeserializeJsonWithPath {
4    fn json_with_path<T: serde::de::DeserializeOwned>(self) -> Result<T>;
5}
6
7impl DeserializeJsonWithPath for String {
8    fn json_with_path<T: serde::de::DeserializeOwned>(self) -> Result<T> {
9        serde_json::from_str(&self).map_err(|source| Error::Json { source })
10    }
11}
12
13impl DeserializeJsonWithPath for reqwest::blocking::Response {
14    fn json_with_path<T: serde::de::DeserializeOwned>(self) -> Result<T> {
15        let bytes =
16            self.bytes().map_err(|source| Error::Reqwest { source })?;
17        serde_json::from_slice(&bytes)
18            .map_err(|source| Error::Json { source })
19    }
20}
21
22pub trait DeserializeJsonWithPathAsync {
23    #[allow(async_fn_in_trait)]
24    async fn json_with_path<T: serde::de::DeserializeOwned>(
25        self,
26    ) -> Result<T>;
27}
28
29impl DeserializeJsonWithPathAsync for reqwest::Response {
30    async fn json_with_path<T: serde::de::DeserializeOwned>(
31        self,
32    ) -> Result<T> {
33        let bytes = self
34            .bytes()
35            .await
36            .map_err(|source| Error::Reqwest { source })?;
37        serde_json::from_slice(&bytes)
38            .map_err(|source| Error::Json { source })
39    }
40}