brawl-api 0.1.2

A Rust implementation of the Brawl Stars API (https://developer.brawlstars.com/).
Documentation
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Contains models for the `/rankings/:country_code/clubs?limit=x` Brawl Stars API endpoint.
//! Included by the feature `"rankings"`; removing that feature will disable the usage of this module.

use serde::{self, Serialize, Deserialize};
use crate::traits::{PropLimRouteable, PropLimFetchable};
use crate::serde::one_default;
use std::ops::{Deref, DerefMut};
use crate::util::fetch_route;
use crate::error::Result;

#[cfg(feature = "async")]
use async_trait::async_trait;

#[cfg(feature = "async")]
use crate::util::a_fetch_route;
use crate::http::Client;
use crate::http::routes::Route;

/// Represents a leaderboard of [`ClubRanking`]s - the top x clubs in a regional or global
/// leaderboard.
///
/// **NOTE:** The API only allows fetching up to the top 200 clubs.
///
/// [`ClubRanking`]: ./struct.ClubRanking.html
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClubLeaderboard {
    /// The clubs in the ranking.
    #[serde(default)]
    pub items: Vec<ClubRanking>,
}

impl Deref for ClubLeaderboard {
    type Target = Vec<ClubRanking>;

    /// Obtain the clubs in the ranking - dereferencing returns the [`items`] field.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use brawl_api::{Client, ClubLeaderboard, traits::*};
    ///
    /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let client = Client::new("my auth token");
    /// let top50clubs = ClubLeaderboard::fetch(
    ///     &client,   // <- the client containing the auth key
    ///     "global",  // <- the region of the leaderboard to fetch ("global" - world-wide)
    ///     50         // <- limit of rankings to fetch (i.e. top 50)
    /// )?;
    ///
    /// assert_eq!(top50clubs.items, *top50clubs);
    ///
    /// #     Ok(())
    /// # }
    ///
    /// ```
    ///
    /// [`items`]: #structfield.items
    fn deref(&self) -> &Vec<ClubRanking> {
        &self.items
    }
}

impl DerefMut for ClubLeaderboard {
    /// Obtain the clubs in the ranking - dereferencing returns the [`items`] field.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use brawl_api::{Client, ClubLeaderboard, traits::*};
    ///
    /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let client = Client::new("my auth token");
    /// let top50clubs = ClubLeaderboard::fetch(
    ///     &client,   // <- the client containing the auth key
    ///     "global",  // <- the region of the leaderboard to fetch ("global" - world-wide)
    ///     50         // <- limit of rankings to fetch (i.e. top 50)
    /// )?;
    ///
    /// assert_eq!(top50clubs.items, *top50clubs);
    ///
    /// #     Ok(())
    /// # }
    ///
    /// ```
    ///
    /// [`items`]: #structfield.items
    fn deref_mut(&mut self) -> &mut Vec<ClubRanking> {
        &mut self.items
    }
}

#[cfg_attr(feature = "async", async_trait)]
impl PropLimFetchable for ClubLeaderboard {
    type Property = str;
    type Limit = u8;

    /// (Sync) Fetches the top `limit <= 200` clubs in the regional (two-letter) `country_code`
    /// leaderboard (or global leaderboard, if `country_code == "global"`).
    ///
    /// # Errors
    ///
    /// This function may error:
    /// - While requesting (will return an [`Error::Request`]);
    /// - After receiving a bad status code (API or other error - returns an [`Error::Status`]);
    /// - After a ratelimit is indicated by the API, while also specifying when it is lifted ([`Error::Ratelimited`]);
    /// - While parsing incoming JSON (will return an [`Error::Json`]).
    ///
    /// (All of those, of course, wrapped inside an `Err`.)
    ///
    /// # Examples
    ///
    /// World-wide club leaderboard:
    /// ```rust,ignore
    /// use brawl_api::{ClubLeaderboard, Client, traits::PropLimFetchable};
    ///
    /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let client = Client::new("my auth key");
    ///
    /// // if the fetch is successful, then the variable below will have the global top 100 clubs
    /// // in the 'items' field (i.e. '*top100clubs').
    /// let top100clubs: ClubLeaderboard = ClubLeaderboard::fetch(&client, "global", 100)?;
    ///
    /// // get club ranked #1. The items are usually sorted (i.e. rank 1 on index [0], rank 2
    /// // on index [1] etc.), but, to make the program absolutely safe, might want to .sort()
    /// let club1 = &top100clubs[0];
    ///
    /// assert_eq!(club1.rank, 1);
    ///
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Regional (in this case, zimbabwean) club leaderboard:
    /// ```rust,ignore
    /// use brawl_api::{ClubLeaderboard, Client, traits::PropLimFetchable};
    ///
    /// # async fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let client = Client::new("my auth key");
    ///
    /// // if the fetch is successful, then the variable below will have the top 100 zimbabwean clubs
    /// // in the 'items' field (i.e. '*top100zwclubs').
    /// let top100zwclubs: ClubLeaderboard = ClubLeaderboard::fetch(&client, "ZW", 100)?;
    ///
    /// // get club ranked #1. The items are usually sorted (i.e. rank 1 on index [0], rank 2
    /// // on index [1] etc.), but, to make the program absolutely safe, might want to .sort()
    /// let club1 = &top100zwclubs[0];
    ///
    /// assert_eq!(club1.rank, 1);
    ///
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// [`Error::Request`]: error/enum.Error.html#variant.Request
    /// [`Error::Status`]: error/enum.Error.html#variant.Status
    /// [`Error::Ratelimited`]: error/enum.Error.html#variant.Ratelimited
    /// [`Error::Json`]: error/enum.Error.html#variant.Json
    fn fetch(client: &Client, country_code: &str, limit: u8) -> Result<ClubLeaderboard> {
        let route = ClubLeaderboard::get_route(country_code, limit);
        fetch_route::<ClubLeaderboard>(client, &route)
    }

    /// (Async) Fetches the top `limit <= 200` clubs in the regional (two-letter) `country_code`
    /// leaderboard (or global leaderboard, if `country_code == "global"`).
    ///
    /// # Errors
    ///
    /// This function may error:
    /// - While requesting (will return an [`Error::Request`]);
    /// - After receiving a bad status code (API or other error - returns an [`Error::Status`]);
    /// - After a ratelimit is indicated by the API, while also specifying when it is lifted ([`Error::Ratelimited`]);
    /// - While parsing incoming JSON (will return an [`Error::Json`]).
    ///
    /// (All of those, of course, wrapped inside an `Err`.)
    ///
    /// # Examples
    ///
    /// World-wide club leaderboard:
    /// ```rust,ignore
    /// use brawl_api::{ClubLeaderboard, Client, traits::PropLimFetchable};
    ///
    /// let client = Client::new("my auth key");
    ///
    /// // if the fetch is successful, then the variable below will have the global top 100 clubs
    /// // in the 'items' field (i.e. '*top100clubs').
    /// let top100clubs: ClubLeaderboard = ClubLeaderboard::a_fetch(&client, "global", 100).await?;
    ///
    /// // get club ranked #1. The items are usually sorted (i.e. rank 1 on index [0], rank 2
    /// // on index [1] etc.), but, to make the program absolutely safe, might want to .sort()
    /// let club1 = &top100clubs[0];
    ///
    /// # Ok::<(), Box<dyn ::std::error::Error>>(())
    /// ```
    ///
    /// Regional (in this case, zimbabwean) club leaderboard:
    /// ```rust,ignore
    /// use brawl_api::{ClubLeaderboard, Client, traits::PropLimFetchable};
    ///
    /// # async fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let client = Client::new("my auth key");
    ///
    /// // if the fetch is successful, then the variable below will have the top 100 zimbabwean clubs
    /// // in the 'items' field (i.e. '*top100zwclubs').
    /// let top100zwclubs: ClubLeaderboard = ClubLeaderboard::a_fetch(&client, "ZW", 100).await?;
    ///
    /// // get club ranked #1. The items are usually sorted (i.e. rank 1 on index [0], rank 2
    /// // on index [1] etc.), but, to make the program absolutely safe, might want to .sort()
    /// let club1 = &top100zwclubs[0];
    ///
    /// assert_eq!(club1.rank, 1);
    ///
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// [`Error::Request`]: error/enum.Error.html#variant.Request
    /// [`Error::Status`]: error/enum.Error.html#variant.Status
    /// [`Error::Ratelimited`]: error/enum.Error.html#variant.Ratelimited
    /// [`Error::Json`]: error/enum.Error.html#variant.Json
    #[cfg(feature="async")]
    async fn a_fetch(
        client: &Client, country_code: &'async_trait str, limit: u8
    ) -> Result<ClubLeaderboard>
        where Self: 'async_trait,
              Self::Property: 'async_trait,
    {
        let route = ClubLeaderboard::get_route(&country_code, limit);
        a_fetch_route::<ClubLeaderboard>(client, &route).await
    }
}

impl PropLimRouteable for ClubLeaderboard {
    type Property = str;
    type Limit = u8;

    /// Get the route for fetching the top `limit` clubs in the regional `country_code`
    /// leaderboard (or global, if `country_code == "global"`).
    fn get_route(country_code: &str, limit: u8) -> Route {
        Route::ClubRankings {
            country_code: country_code.to_owned(),
            limit
        }
    }
}

/// Represents a club's ranking, based on a regional or global leaderboard.
/// To obtain the club's full data (a [`Club`] instance), see [`Club::fetch_from`].
///
/// [`Club`]: ../clubs/club/struct.Club.html
/// [`Club::fetch_from`]: ../clubs/club/struct.Club.html#method.fetch_from
#[derive(Debug, Hash, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClubRanking {
    /// The club's tag.
    #[serde(default)]
    pub tag: String,

    /// The club's name.
    #[serde(default)]
    pub name: String,

    /// The club's current trophies.
    #[serde(default)]
    pub trophies: usize,

    /// The club's current rank in the leaderboard.
    #[serde(default = "one_default")]
    pub rank: u8,

    /// The amount of members in this club.
    #[serde(default)]
    pub member_count: usize,
}

impl Default for ClubRanking {
    /// Returns an instance of `ClubRanking` with initial values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use brawl_api::ClubRanking;
    ///
    /// assert_eq!(
    ///     ClubRanking::default(),
    ///     ClubRanking {
    ///         tag: String::from(""),
    ///         name: String::from(""),
    ///         trophies: 0,
    ///         rank: 1,
    ///         member_count: 0,
    ///     }
    /// );
    /// ```
    fn default() -> ClubRanking {
        ClubRanking {
            tag: String::from(""),
            name: String::from(""),
            trophies: 0,
            rank: 1,
            member_count: 0,
        }
    }
}

impl PartialOrd for ClubRanking {
    /// Compares and determines which `ClubRanking` has a higher rank (i.e., smaller rank number).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use brawl_api::{ClubLeaderboard, traits::*};
    ///
    /// # use brawl_api::ClubRanking;
    ///
    /// let leaderboard: ClubLeaderboard;
    ///
    /// # leaderboard = ClubLeaderboard {
    /// #     items: vec![
    /// #         ClubRanking { rank: 1, ..ClubRanking::default() },  // #1 position
    /// #         ClubRanking { rank: 2, ..ClubRanking::default() },  // #2 position
    /// #     ]
    /// # };
    ///
    /// // after fetching the leaderboard (see examples in ClubLeaderboard::fetch)...
    ///
    /// let (club_1, club_2) = (&leaderboard[0], &leaderboard[1]);
    /// // generally, the first club is the one with 'rank' field equal to 1 and the second,
    /// // 'rank' field equal to 2, so assume this is true (the API generally sends them sorted,
    /// // but, to guarantee strictness, one can 'leaderboard.sort()'.
    ///
    /// assert!(club_1 > club_2)  // smaller rank number = higher position
    /// ```
    ///
    /// [`ClubLeaderboard`]: struct.ClubLeaderboard.html
    fn partial_cmp(&self, other: &ClubRanking) -> Option<::std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ClubRanking {
    /// Compares and determines which `ClubRanking` has a higher rank (i.e., smaller rank number).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use brawl_api::{ClubLeaderboard, traits::*};
    ///
    /// # use brawl_api::ClubRanking;
    ///
    /// let leaderboard: ClubLeaderboard;
    ///
    /// # leaderboard = ClubLeaderboard {
    /// #     items: vec![
    /// #         ClubRanking { rank: 1, ..ClubRanking::default() },  // #1 position
    /// #         ClubRanking { rank: 2, ..ClubRanking::default() },  // #2 position
    /// #     ]
    /// # };
    ///
    /// // after fetching the leaderboard (see examples in ClubLeaderboard::fetch)...
    ///
    /// let (club_1, club_2) = (&leaderboard[0], &leaderboard[1]);
    /// // generally, the first club is the one with 'rank' field equal to 1 and the second,
    /// // 'rank' field equal to 2, so assume this is true (the API generally sends them sorted,
    /// // but, to guarantee strictness, one can 'leaderboard.sort()'.
    ///
    /// assert!(club_1 > club_2)  // smaller rank number = higher position
    /// ```
    ///
    /// [`ClubLeaderboard`]: struct.ClubLeaderboard.html
    fn cmp(&self, other: &ClubRanking) -> ::std::cmp::Ordering {
        self.rank.cmp(&other.rank).reverse()
    }
}

///////////////////////////////////   tests   ///////////////////////////////////

#[cfg(test)]
mod tests {
    use serde_json;
    use super::{ClubLeaderboard, ClubRanking};
    use crate::error::Error;

    /// Tests for ClubLeaderboard deserialization from API-provided JSON.
    #[test]
    fn rankings_clubs_deser() -> Result<(), Box<dyn ::std::error::Error>> {

        let rc_json_s = r##"{
  "items": [
    {
      "tag": "#AAAAAAAAA",
      "name": "Club",
      "trophies": 30000,
      "rank": 1,
      "memberCount": 50
    },
    {
      "tag": "#EEEEEEE",
      "name": "Also Club",
      "trophies": 25000,
      "rank": 2,
      "memberCount": 30
    },
    {
      "tag": "#QQQQQQQ",
      "name": "Clubby Club",
      "trophies": 23000,
      "rank": 3,
      "memberCount": 25
    },
    {
      "tag": "#55555553Q",
      "name": "Not a valid club",
      "trophies": 20000,
      "rank": 4,
      "memberCount": 10
    }
  ]
}"##;

        let c_leaders = serde_json::from_str::<ClubLeaderboard>(rc_json_s)
            .map_err(Error::Json)?;

        assert_eq!(
            c_leaders,
            ClubLeaderboard {
                items: vec![
                    ClubRanking {
                        tag: String::from("#AAAAAAAAA"),
                        name: String::from("Club"),
                        member_count: 50,
                        trophies: 30000,
                        rank: 1,
                    },
                    ClubRanking {
                        tag: String::from("#EEEEEEE"),
                        name: String::from("Also Club"),
                        member_count: 30,
                        trophies: 25000,
                        rank: 2,
                    },
                    ClubRanking {
                        tag: String::from("#QQQQQQQ"),
                        name: String::from("Clubby Club"),
                        member_count: 25,
                        trophies: 23000,
                        rank: 3,
                    },
                    ClubRanking {
                        tag: String::from("#55555553Q"),
                        name: String::from("Not a valid club"),
                        member_count: 10,
                        trophies: 20000,
                        rank: 4,
                    }
                ]
            }
        );

        Ok(())
    }
}