battlebit_api/
api.rs

1use reqwest::Url;
2
3#[cfg(target_arch = "wasm32")]
4use reqwest::get;
5
6#[cfg(not(target_arch = "wasm32"))]
7use reqwest::blocking::get;
8
9use crate::endpoints;
10use crate::error::Error;
11
12fn fix_bom(data: &[u8]) -> &[u8] {
13    if data.starts_with(&[0xEF, 0xBB, 0xBF]) {
14        &data[3..]
15    } else {
16        data
17    }
18}
19
20/// BattleBit API Struct
21#[derive(Clone, PartialEq, Debug)]
22pub struct BBApi(Url);
23
24impl BBApi {
25
26    /// Shorthand for `BBApi::Default()`  
27    /// Creates a new BBApi with the default URL
28    pub fn new() -> BBApi {
29        BBApi::default()
30    }
31
32    /// Creates a new BBApi with the given URL
33    pub fn with_url(url: Url) -> BBApi {
34        BBApi(url)
35    }
36
37    /// Fetches the server list and puts it into a `Vec<ServerData>`
38    #[cfg(target_arch = "wasm32")]
39    pub async fn server_list(&self) -> Result<Vec<endpoints::ServerData>, Error> {
40        let url = self.0.join("Servers/GetServerList")?;
41        let data = get(url).await?.bytes().await?;
42        let data = serde_json::from_slice(fix_bom(&data))?;
43
44        Ok(data)
45    }
46
47    /// Fetches the server list and puts it into a `Vec<ServerData>`
48    #[cfg(not(target_arch = "wasm32"))]
49    pub fn server_list(&self) -> Result<Vec<endpoints::ServerData>, Error> {
50        let url = self.0.join("Servers/GetServerList")?;
51        let data = get(url)?.bytes()?;
52        let data = serde_json::from_slice(fix_bom(&data))?;
53
54        Ok(data)
55    }
56
57    /// Fetches the leaderboard.
58    #[cfg(target_arch = "wasm32")]
59    pub async fn leaderboard(&self) -> Result<endpoints::Leaderboard, Error> {
60        let url = self.0.join("Leaderboard/Get")?;
61        let data = get(url).await?.bytes().await?;
62        let result: Vec<endpoints::Leaderboards> = serde_json::from_slice(fix_bom(&data))?;
63        Ok(endpoints::Leaderboard::from(result))
64    }
65
66    /// Fetches the leaderboard.
67    #[cfg(not(target_arch = "wasm32"))]
68    pub fn leaderboard(&self) -> Result<endpoints::Leaderboard, Error> {
69        let url = self.0.join("Leaderboard/Get")?;
70        let data = get(url)?.bytes()?;
71        let result: Vec<endpoints::Leaderboards> = serde_json::from_slice(fix_bom(&data))?;
72        Ok(endpoints::Leaderboard::from(result))
73    }
74}
75
76impl Default for BBApi {
77    /// Creates a new BBApi with the default URL  
78    /// Default URL is `https://publicapi.battlebit.cloud/`
79    fn default() -> Self {
80        Self(Url::parse("https://publicapi.battlebit.cloud/").unwrap())
81    }
82}