Skip to main content

api_swgoh_gg/
lib.rs

1extern crate log;
2extern crate reqwest;
3#[macro_use]
4extern crate serde;
5
6use model::{Ability, Gear, Ship, Unit};
7
8pub mod model;
9
10const BASE_API_URL: &str = "https://swgoh.gg/api/";
11
12#[macro_export]
13macro_rules! get_url {
14    ($p:expr) => {
15        format!("{}{}/", BASE_API_URL, $p)
16    };
17    ($p:expr, $i:expr) => {
18        format!("{}{}/{}/", BASE_API_URL, $p, $i)
19    };
20}
21
22#[macro_export]
23macro_rules! execute_get {
24    ($url: expr) => {
25        reqwest::blocking::get(&$url)?.json()
26    };
27}
28
29pub type Reply<T> = reqwest::Result<T>;
30
31/// Get all abilities
32pub fn get_abilities() -> Reply<Vec<Ability>> {
33    execute_get!(get_url!("abilities"))
34}
35
36/// Get all gears
37pub fn get_gears() -> Reply<Vec<Gear>> {
38    execute_get!(get_url!("gear"))
39}
40
41/// Get a gear with id
42pub fn get_gear(id: u64) -> Reply<Gear> {
43    execute_get!(get_url!("gear", id))
44}
45
46/// Get all ships
47pub fn get_ships() -> Reply<Vec<Ship>> {
48    execute_get!(get_url!("ships"))
49}
50
51/// Get a ship with id
52pub fn get_ship(id: u64) -> Reply<Ship> {
53    execute_get!(get_url!("ships", id))
54}
55
56/// Get all units
57pub fn get_units() -> Reply<Vec<Unit>> {
58    execute_get!(get_url!("characters"))
59}
60
61/// Gat a unit with id
62pub fn get_unit(id: u64) -> Reply<Unit> {
63    execute_get!(get_url!("characters", id))
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn abilities_works() {
72        get_abilities().unwrap();
73    }
74
75    #[test]
76    fn gears_works() {
77        get_gears().unwrap();
78    }
79
80    #[test]
81    fn gear_works() {
82        get_gear(1).unwrap();
83    }
84
85    #[test]
86    fn ships_works() {
87        get_ships().unwrap();
88    }
89
90    #[test]
91    fn ship_works() {
92        get_ship(1).unwrap();
93    }
94
95    #[test]
96    fn units_works() {
97        let units = get_units().unwrap();
98        let mt: Vec<&Unit> = units.iter().filter(|u| u.pk == 200).collect();
99
100        assert_eq!(mt.len(), 1);
101        assert_eq!(&mt[0].name, "Darth Vader");
102    }
103
104    #[test]
105    fn unit_works() {
106        let unit = get_unit(200).unwrap();
107
108        assert_eq!("Darth Vader", &unit.name);
109    }
110}