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
use reqwest::StatusCode;
use std::borrow::Cow;
const BASE_URL: &str = "https://api.themoviedb.org/3";
#[cfg(feature = "commands")]
pub struct Client {
client: reqwest::Client,
base_url: Cow<'static, str>,
api_key: String,
}
#[cfg(feature = "commands")]
impl Client {
pub fn new(api_key: String) -> Self {
Self {
client: reqwest::Client::default(),
base_url: Cow::Borrowed(BASE_URL),
api_key,
}
}
#[cfg(test)]
pub fn with_base_url(mut self, base_url: String) -> Self {
self.base_url = Cow::Owned(base_url);
self
}
pub async fn execute<T: serde::de::DeserializeOwned>(
&self,
path: &str,
mut params: Vec<(&str, Cow<'_, str>)>,
) -> Result<T, crate::error::Error> {
params.push(("api_key", Cow::Borrowed(self.api_key.as_str())));
let url = format!("{}{}", self.base_url, path);
let res = self.client.get(url).query(¶ms).send().await?;
let status_code = res.status();
if status_code.is_success() {
Ok(res.json::<T>().await?)
} else if status_code == StatusCode::UNPROCESSABLE_ENTITY {
let payload: crate::error::ServerValidationBodyError = res.json().await?;
Err(crate::error::Error::from((status_code, payload.into())))
} else {
let payload: crate::error::ServerOtherBodyError = res.json().await?;
Err(crate::error::Error::from((status_code, payload.into())))
}
}
}