twitch_helix/
client.rs

1//! Helix client
2
3// Imports
4use crate::{HelixRequest, HelixResponse, OAuthRequest, OAuthResponse};
5use reqwest as req;
6
7/// A client to make requests to Helix with.
8///
9/// The client is initialized given an initial oauth string.
10/// This allows you to do a [`OAuthRequest`] for validating
11/// this token and getting a client id, which may then be used
12/// to make [`HelixRequest`]
13#[derive(Clone, Debug)]
14pub struct Client {
15	/// Underlying client
16	client: req::Client,
17
18	/// OAuth token
19	oauth: String,
20}
21
22/// Error type for [`Client::request_oauth`] and [`Client::request_helix`]
23#[derive(Debug, thiserror::Error)]
24pub enum RequestError {
25	/// Unable to send request
26	#[error("Unable to send request")]
27	Send(#[source] req::Error),
28
29	/// Unable to parse response
30	#[error("Unable to parse response")]
31	Parse(#[source] req::Error),
32}
33
34impl Client {
35	/// Creates a new client given an oauth token
36	#[must_use]
37	pub fn new(oauth: String) -> Self {
38		Self {
39			client: req::Client::new(),
40			oauth,
41		}
42	}
43
44	/// Performs an OAuth request to twitch
45	pub async fn request_oauth<R: OAuthRequest + Send + Sync>(&mut self, request: &R) -> Result<OAuthResponse<R::Response>, RequestError> {
46		// Get url
47		let url = request.url();
48
49		// Build the request and send it
50		let response = self
51			.client
52			.get(url)
53			.header("Authorization", format!("OAuth {}", self.oauth))
54			.send()
55			.await
56			.map_err(RequestError::Send)?;
57
58		// Then parse the response
59		let output = response.json().await.map_err(RequestError::Parse)?;
60
61		Ok(output)
62	}
63
64	/// Performs a request to Helix
65	pub async fn request_helix<R: HelixRequest + Send + Sync>(
66		&mut self, request: &R, client_id: &str,
67	) -> Result<HelixResponse<R::Response>, RequestError> {
68		// Get url
69		let url = request.url();
70
71		// Build the request and send it
72		let response = self
73			.client
74			.request(request.http_method(), url)
75			.bearer_auth(&self.oauth)
76			.header("Client-ID", client_id)
77			.send()
78			.await
79			.map_err(RequestError::Send)?;
80
81		// Then parse the response
82		let output = response.json().await.map_err(RequestError::Parse)?;
83
84		Ok(output)
85	}
86}