1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use bytes::Bytes;
use reqwest::{Response, StatusCode};
use serde::de::DeserializeOwned;
use std::future::Future;
use std::ops::{Deref, DerefMut};

/// Data which can be extracted from a [`Response`].
pub trait Data: Sized {
    fn from_response(response: Response) -> impl Future<Output = Result<Self, reqwest::Error>>;
}

/// String data
impl Data for String {
    async fn from_response(response: Response) -> Result<Self, reqwest::Error> {
        response.error_for_status()?.text().await
    }
}

/// BLOB data
impl Data for Bytes {
    async fn from_response(response: Response) -> Result<Self, reqwest::Error> {
        response.error_for_status()?.bytes().await
    }
}

/// A new-type wrapping [`String`].
pub struct Text(pub String);

impl Data for Text {
    async fn from_response(response: Response) -> Result<Self, reqwest::Error> {
        response.error_for_status()?.text().await.map(Self)
    }
}

impl Text {
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl Deref for Text {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Text {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// JSON based data.
pub struct Json<D>(pub D)
where
    D: DeserializeOwned;

impl<D> Data for Json<D>
where
    D: DeserializeOwned,
{
    async fn from_response(response: Response) -> Result<Self, reqwest::Error> {
        response.error_for_status()?.json().await.map(Self)
    }
}

impl<D: DeserializeOwned> Json<D> {
    #[inline]
    pub fn into_inner(self) -> D {
        self.0
    }
}

impl<D: DeserializeOwned> Deref for Json<D> {
    type Target = D;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<D: DeserializeOwned> DerefMut for Json<D> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<D: Data> Data for Option<D> {
    async fn from_response(response: Response) -> Result<Self, reqwest::Error> {
        if response.status() == StatusCode::NOT_FOUND {
            return Ok(None);
        }

        Ok(Some(D::from_response(response).await?))
    }
}