-
Notifications
You must be signed in to change notification settings - Fork 11
/
client.rs
225 lines (197 loc) · 6.58 KB
/
client.rs
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
//! Defines the client used to access Pokeapi.
use http_cache_reqwest::{Cache, CacheManager, HttpCache, HttpCacheOptions};
use reqwest::{Client, IntoUrl, Url};
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use serde::de::DeserializeOwned;
use crate::error::Error;
// Reexport to ease overloading.
pub use http_cache_reqwest::{CacheMode, CacheOptions};
#[cfg(feature = "filesystem-cache")]
pub use http_cache_reqwest::CACacheManager;
#[cfg(feature = "in-memory-cache")]
pub use http_cache_reqwest::MokaManager;
/// Environment to target while calling PokeApi.
#[derive(Clone)]
pub enum Environment {
/// Targets the production environment.
Production,
/// Targets the stating environment.
Staging,
/// Targets a custom environment of PokeApi, a local deployment through Docker for example.
Custom(String),
}
impl Default for Environment {
fn default() -> Self {
Self::Production
}
}
impl TryFrom<Environment> for Url {
type Error = Error;
fn try_from(value: Environment) -> Result<Self, Self::Error> {
match value {
Environment::Production => Ok(Url::parse("https://pokeapi.co/api/v2/").unwrap()),
Environment::Staging => Ok(Url::parse("https://staging.pokeapi.co/api/v2/").unwrap()),
Environment::Custom(mut s) => {
if !s.ends_with('/') {
s.push('/');
}
Url::parse(&s).map_err(|_| Error::UrlParse(s))
}
}
}
}
/// Builder used to ease the configuration of `RustemonClient`.
pub struct RustemonClientBuilder<T: CacheManager> {
cache: HttpCache<T>,
environment: Environment,
}
#[cfg(feature = "filesystem-cache")]
impl Default for RustemonClientBuilder<CACacheManager> {
fn default() -> Self {
Self {
cache: HttpCache {
mode: CacheMode::Default,
manager: CACacheManager::default(),
options: HttpCacheOptions::default(),
},
environment: Environment::default(),
}
}
}
#[cfg(feature = "in-memory-cache")]
impl Default for RustemonClientBuilder<MokaManager> {
fn default() -> Self {
Self {
cache: HttpCache {
mode: CacheMode::Default,
manager: MokaManager::default(),
options: HttpCacheOptions::default(),
},
environment: Environment::default(),
}
}
}
impl<T: CacheManager> RustemonClientBuilder<T> {
/// Configure the CacheMode of the builder. See [CacheMode].
pub fn with_mode(mut self, cache_mode: CacheMode) -> Self {
self.cache.mode = cache_mode;
self
}
/// Configure the manager of the builder. See [CacheManager].
pub fn with_manager(mut self, manager: T) -> Self {
self.cache.manager = manager;
self
}
/// Configure the cache options of the builder. See [CacheOptions].
pub fn with_options(mut self, options: CacheOptions) -> Self {
self.cache.options.cache_options = Some(options);
self
}
/// Configure the environment of the builder. See [Environment].
pub fn with_environment(mut self, environment: Environment) -> Self {
self.environment = environment;
self
}
/// Consumes the builder in order to create a [RustemonClient].
pub fn try_build(self) -> Result<RustemonClient, Error> {
Ok(RustemonClient {
client: ClientBuilder::new(Client::new())
.with(Cache(self.cache))
.build(),
base: Url::try_from(self.environment.clone())?,
})
}
}
/// Custom client used to call Pokeapi.
#[derive(Debug)]
pub struct RustemonClient {
client: ClientWithMiddleware,
base: Url,
}
/// Inner representation of an endpoint's id. Used to ease the api calls.
pub(crate) enum Id<'a> {
Int(i64),
Str(&'a str),
}
impl RustemonClient {
/// Calls the api through the given [Url].
async fn inner_get<T>(&self, url: Url) -> Result<T, Error>
where
T: DeserializeOwned,
{
Ok(self.client.get(url).send().await?.json().await?)
}
/// Make a call through the client to the given `endpoint`.
pub(crate) async fn get_by_endpoint<T>(&self, endpoint: &str) -> Result<T, Error>
where
T: DeserializeOwned,
{
let url = self
.base
.join(endpoint)
.map_err(|_| Error::UrlParse(format!("{}/{endpoint}", self.base)))?;
self.inner_get(url).await
}
/// Make a call through the client to the given `endpoint`, adding `limit` and `offset` to the query.
pub(crate) async fn get_with_limit_and_offset<T>(
&self,
endpoint: &str,
limit: i64,
offset: i64,
) -> Result<T, Error>
where
T: DeserializeOwned,
{
let mut url = self
.base
.join(endpoint)
.map_err(|_| Error::UrlParse(format!("{}/{endpoint}", self.base)))?;
url.set_query(Some(&format!("limit={limit}&offset={offset}")));
self.inner_get(url).await
}
/// Make a call though the client to the given `endpoint`, targetting a specific resource described by [Id].
pub(crate) async fn get_by_endpoint_and_id<'a, T>(
&self,
endpoint: &str,
id: Id<'a>,
) -> Result<T, Error>
where
T: DeserializeOwned,
{
let inner_id = match id {
Id::Int(i) => i.to_string(),
Id::Str(s) => s.to_owned(),
};
let url = self
.base
.join(&format!("{endpoint}/{inner_id}"))
.map_err(|_| Error::UrlParse(format!("{}/{endpoint}/{inner_id}", self.base)))?;
self.inner_get(url).await
}
/// Make a call through the client from a given [IntoUrl].
pub(crate) async fn get_by_url<T>(&self, url: impl IntoUrl) -> Result<T, Error>
where
T: DeserializeOwned,
{
self.inner_get(url.into_url()?).await
}
}
impl Default for RustemonClient {
/// Returns a RustemonClient with default configuration.
fn default() -> Self {
#[cfg(feature = "filesystem-cache")]
let manager = CACacheManager::default();
#[cfg(feature = "in-memory-cache")]
let manager = MokaManager::default();
Self {
client: ClientBuilder::new(Client::new())
.with(Cache(HttpCache {
mode: CacheMode::Default,
manager,
options: HttpCacheOptions::default(),
}))
.build(),
base: Url::try_from(Environment::default()).unwrap(),
}
}
}