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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//! Client for interacting with the Codewars REST API
use std::string::ToString;
use crate::rest_api::models::{AuthoredChallenges, CodeChallenge, CompletedChallenges, User};
/// Client for interacting with the Codewars API
#[derive(Clone)]
pub struct RestCodewarsClient {
host_name: String
}
/// Implementation of RestCodewarsClient
impl RestCodewarsClient {
/// Create new instance of RestCodewarsClient
///
/// # Examples
///
/// ```
/// use codewars_api::rest_api::client::RestCodewarsClient;
///
/// // We use Tokio here, because all functions of client is asynchronous
/// #[tokio::main]
/// async fn main() {
/// let client = RestCodewarsClient::new();
/// // We can use methods of client here
/// }
/// ```
pub fn new() -> Self {
Self {
host_name: "https://www.codewars.com".to_string()
}
}
/// Create new instance of RestCodewarsClient with custom host name
/// Currently this used for unit tests
#[doc(hidden)]
pub(crate) fn new_with_custom_host(host_name: String) -> Self {
Self {
host_name
}
}
/// Get info about user by username
///
/// # Arguments:
/// * username (&str) - username of the user
///
/// # Returns:
/// * Result<User, String> - Result that contains the user or an error message
///
/// # Errors:
/// * `unexpected status code: {status_code}` - If the status code is not 200
/// * `error decoding response body` - If there is an error decoding the response body with serde
///
/// # Examples
/// ```no_run
/// # use codewars_api::rest_api::client::RestCodewarsClient;
/// # #[tokio::main]
/// # async fn main() {
/// # let client = RestCodewarsClient::new();
/// let user = client.get_user("ANKDDEV").await.unwrap();
/// // Get name of user
/// println!("Name: {}", user.name);
/// // Get leaderboard position of user
/// println!("Leaderboard position: {}", user.leaderboard_position);
/// # }
/// ```
pub async fn get_user(&self, username: &str) -> Result<User, String> {
// Send request
let response = reqwest::get(format!(
"{}/api/v1/users/{}",
self.host_name, username
))
.await
.unwrap();
// Check status code
match response.status() {
reqwest::StatusCode::OK => match response.json::<User>().await {
// Return parsed response
Ok(parsed) => Ok(parsed),
// Return error if there is an error decoding the response body with serde
Err(err) => Err(err.to_string()),
},
// Return error if status code is not 200
other => Err(format!("unexpected status code: {}", other)),
}
}
/// Get info about kata by slug
///
/// # Arguments:
/// * slug (&str) - slug of the kata
///
/// # Returns:
/// * Result<CodeChallenge, String> - Result that contains the kata or an error message
///
/// # Errors:
/// * `unexpected status code: {status_code}` - If the status code is not 200
/// * `error decoding response body` - If there is an error decoding the response body with serde
///
/// # Examples
/// ```no_run
/// # use codewars_api::rest_api::client::RestCodewarsClient;
/// # #[tokio::main]
/// # async fn main() {
/// # let client = RestCodewarsClient::new();
/// let kata = client.get_kata("576bb71bbbcf0951d5000044").await.unwrap();
/// // Get name of code challenge
/// println!("Name: {}", kata.name);
/// // Get slug of code challenge
/// println!("Slug: {}", kata.slug);
/// # }
/// ```
pub async fn get_kata(&self, slug: &str) -> Result<CodeChallenge, String> {
// Send request
let response = reqwest::get(format!(
"{}/api/v1/code-challenges/{}",
self.host_name, slug
))
.await
.unwrap();
// Check status code
match response.status() {
reqwest::StatusCode::OK => match response.json::<CodeChallenge>().await {
// Return parsed response
Ok(parsed) => Ok(parsed),
// Return error if there is an error decoding the response body with serde
Err(err) => Err(err.to_string()),
},
// Return error if status code is not 200
other => Err(format!("unexpected status code: {}", other)),
}
}
/// Get list of completed challenges
///
/// # Arguments:
/// * username (&str) - username of the user
/// * page (u16) - page number
///
/// # Returns:
/// * Result<CompletedChallenges, String> - Result that contains the list of completed challenges or an error message
///
/// # Errors:
/// * `unexpected status code: {status_code}` - If the status code is not 200
/// * `error decoding response body` - If there is an error decoding the response body with serde///
///
/// # Examples
/// ```no_run
/// # use codewars_api::rest_api::client::RestCodewarsClient;
/// # #[tokio::main]
/// # async fn main() {
/// # let client = RestCodewarsClient::new();
/// let challenges = client.get_completed_challenges("ANKDDEV", 0).await.unwrap();
/// // Get total number of pages
/// println!("Total pages: {}", challenges.total_pages);
/// // Get total number of items
/// println!("Total items: {}", challenges.total_items);
/// # }
/// ```
pub async fn get_completed_challenges(
&self,
username: &str,
page: u16,
) -> Result<CompletedChallenges, String> {
// Send request
let response = reqwest::get(format!(
"{}/api/v1/users/{}/code-challenges/completed?page={}",
self.host_name, username, page
))
.await
.unwrap();
// Check status code
match response.status() {
reqwest::StatusCode::OK => match response.json::<CompletedChallenges>().await {
// Return parsed response
Ok(parsed) => Ok(parsed),
// Return error if there is an error decoding the response body with serde
Err(err) => Err(err.to_string()),
},
// Return error if status code is not 200
other => Err(format!("unexpected status code: {}", other)),
}
}
/// Get first page of completed challenges
///
/// # Arguments:
/// * username (&str) - username of the user
///
/// # Returns:
/// * Result<CompletedChallenges, String> - Result that contains the list of completed challenges or an error message
///
/// # Errors:
/// * `unexpected status code: {status_code}` - If the status code is not 200
/// * `error decoding response body` - If there is an error decoding the response body with serde
///
/// # Examples
/// ```no_run
/// # use codewars_api::rest_api::client::RestCodewarsClient;
/// # #[tokio::main]
/// # async fn main() {
/// # let client = RestCodewarsClient::new();
/// let challenges = client.get_completed_challenges_first_page("ANKDDEV").await.unwrap();
/// // Get total number of pages
/// println!("Total pages: {}", challenges.total_pages);
/// // Get total number of items
/// println!("Total items: {}", challenges.total_items);
/// # }
/// ```
pub async fn get_completed_challenges_first_page(
&self,
username: &str,
) -> Result<CompletedChallenges, String> {
// Return first page of list
self.get_completed_challenges(username, 0).await
}
/// Get list of authored challenges
///
/// # Arguments:
/// * username (&str) - username of the user
///
/// # Returns:
/// * Result<AuthoredChallenges, String> - Result that contains the list of authored challenges or an error message
///
/// # Errors:
/// * `unexpected status code: {status_code}` - If the status code is not 200
/// * `error decoding response body` - If there is an error decoding the response body with serde
///
/// # Examples
/// ```no_run
/// # use codewars_api::rest_api::client::RestCodewarsClient;
/// # #[tokio::main]
/// # async fn main() {
/// # let client = RestCodewarsClient::new();
/// let challenges = client.get_authored_challenges("Dentzil").await.unwrap();
/// // Get name of first challenge
/// println!("Total pages: {}", challenges.data.first().unwrap().name);
/// # }
/// ```
///
/// ```no_run
/// # use codewars_api::rest_api::client::RestCodewarsClient;
/// # #[tokio::main]
/// # async fn main() {
/// # let client = RestCodewarsClient::new();
/// let challenges = client.get_authored_challenges("aaron.pp").await.unwrap();
/// // Check if list is not empty
/// assert!(!challenges.data.is_empty());
/// # }
/// ```
pub async fn get_authored_challenges(
&self,
username: &str,
) -> Result<AuthoredChallenges, String> {
// Send request
let response = reqwest::get(format!(
"{}/api/v1/users/{}/code-challenges/authored",
self.host_name, username
))
.await
.unwrap();
// Check status code
match response.status() {
reqwest::StatusCode::OK => match response.json::<AuthoredChallenges>().await {
// Return parsed response
Ok(parsed) => Ok(parsed),
// Return error if there is an error decoding the response body with serde
Err(err) => Err(err.to_string()),
},
// Return error if status code is not 200
other => Err(format!("unexpected status code: {}", other)),
}
}
}
/// Implement Default trait for RestCodewarsClient
impl Default for RestCodewarsClient {
// Return default value of RestCodewarsClient
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
//! Tests for REST Client
//! All mocks are from Codewars documentation
use std::path::Path;
use super::{super::models::*, *};
/// Test getting a user
#[tokio::test]
async fn test_get_user() {
let mut server = mockito::Server::new_async().await;
let host = server.host_with_port();
let client = RestCodewarsClient::new_with_custom_host(format!("http://{}", host));
let content = std::fs::read_to_string(Path::new(&"tests/mocks/get_user.json")).unwrap();
let text: User = serde_json::from_str(&content).unwrap();
let mock = server.mock("GET", "/api/v1/users/some_user").with_status(200).with_header("content-type", "application/json").with_body(content).create_async().await;
let result = client.get_user("some_user").await.unwrap();
mock.assert_async().await;
assert_eq!(result, text);
}
/// Test getting completed challenges
#[tokio::test]
async fn test_get_completed_challenges() {
let mut server = mockito::Server::new_async().await;
let host = server.host_with_port();
let client = RestCodewarsClient::new_with_custom_host(format!("http://{}", host));
let content = std::fs::read_to_string(Path::new(&"tests/mocks/get_completed_challenges.json")).unwrap();
let text: CompletedChallenges = serde_json::from_str(&content).unwrap();
let mock = server.mock("GET", "/api/v1/users/some_user/code-challenges/completed?page=0").with_status(200).with_header("content-type", "application/json").with_body(content).create_async().await;
let result = client.get_completed_challenges("some_user", 0).await.unwrap();
mock.assert_async().await;
assert_eq!(result, text);
}
/// Test getting first page of completed challenges
#[tokio::test]
async fn test_get_completed_challenges_first_page() {
let mut server = mockito::Server::new_async().await;
let host = server.host_with_port();
let client = RestCodewarsClient::new_with_custom_host(format!("http://{}", host));
let content = std::fs::read_to_string(Path::new(&"tests/mocks/get_completed_challenges.json")).unwrap();
let text: CompletedChallenges = serde_json::from_str(&content).unwrap();
let mock = server.mock("GET", "/api/v1/users/some_user/code-challenges/completed?page=0").with_status(200).with_header("content-type", "application/json").with_body(content).create_async().await;
let result = client.get_completed_challenges_first_page("some_user").await.unwrap();
mock.assert_async().await;
assert_eq!(result, text);
}
/// Test getting authored challenges
#[tokio::test]
async fn test_get_authored_challenges() {
let mut server = mockito::Server::new_async().await;
let host = server.host_with_port();
let client = RestCodewarsClient::new_with_custom_host(format!("http://{}", host));
let content = std::fs::read_to_string(Path::new(&"tests/mocks/get_authored_challenges.json")).unwrap();
let text: AuthoredChallenges = serde_json::from_str(&content).unwrap();
let mock = server.mock("GET", "/api/v1/users/some_user/code-challenges/authored").with_status(200).with_header("content-type", "application/json").with_body(content).create_async().await;
let result = client.get_authored_challenges("some_user").await.unwrap();
mock.assert_async().await;
assert_eq!(result, text);
}
/// Test getting code challenge information
#[tokio::test]
async fn test_get_code_challenge() {
let mut server = mockito::Server::new_async().await;
let host = server.host_with_port();
let client = RestCodewarsClient::new_with_custom_host(format!("http://{}", host));
let content = std::fs::read_to_string(Path::new(&"tests/mocks/get_challenge.json")).unwrap();
let text: CodeChallenge = serde_json::from_str(&content).unwrap();
let mock = server.mock("GET", format!("/api/v1/code-challenges/{}", text.slug).as_str()).with_status(200).with_header("content-type", "application/json").with_body(content).create_async().await;
let result = client.get_kata(&text.slug).await.unwrap();
mock.assert_async().await;
assert_eq!(result, text);
}
}