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
use crate::{HelixRequest, HelixResponse, OAuthRequest, OAuthResponse};
use reqwest as req;
#[derive(Clone, Debug)]
pub struct Client {
client: req::Client,
oauth: String,
}
#[derive(Debug, thiserror::Error)]
pub enum RequestError {
#[error("Unable to send request")]
Send(#[source] req::Error),
#[error("Unable to parse response")]
Parse(#[source] req::Error),
}
impl Client {
#[must_use]
pub fn new(oauth: String) -> Self {
Self {
client: req::Client::new(),
oauth,
}
}
pub async fn request_oauth<R: OAuthRequest + Send + Sync>(&mut self, request: &R) -> Result<OAuthResponse<R::Response>, RequestError> {
let url = request.url();
let response = self
.client
.get(url)
.header("Authorization", format!("OAuth {}", self.oauth))
.send()
.await
.map_err(RequestError::Send)?;
let output = response.json().await.map_err(RequestError::Parse)?;
Ok(output)
}
pub async fn request_helix<R: HelixRequest + Send + Sync>(
&mut self, request: &R, client_id: &str,
) -> Result<HelixResponse<R::Response>, RequestError> {
let url = request.url();
let response = self
.client
.request(request.http_method(), url)
.bearer_auth(&self.oauth)
.header("Client-ID", client_id)
.send()
.await
.map_err(RequestError::Send)?;
let output = response.json().await.map_err(RequestError::Parse)?;
Ok(output)
}
}