r6stats/
client.rs

1use crate::{
2    types::{
3        ApiResponse,
4        UserData,
5    },
6    Error,
7};
8use std::time::Duration;
9
10/// An R6Stats client
11#[derive(Debug, Clone)]
12pub struct Client {
13    /// The inner http client
14    pub client: reqwest::Client,
15}
16
17impl Client {
18    /// Make a new client.
19    pub fn new() -> Self {
20        let client = reqwest::Client::builder()
21            .connect_timeout(Duration::from_secs(10))
22            .build()
23            .expect("failed to build client");
24
25        Client { client }
26    }
27
28    // TODO: Add non-pc support
29    /// Search for a PC user's profile by name.
30    pub async fn search(&self, name: &str) -> Result<Vec<UserData>, Error> {
31        let url = format!("https://r6stats.com/api/player-search/{name}/pc");
32        let text = self.client.get(&url).send().await?.text().await?;
33        let response: ApiResponse<Vec<UserData>> = serde_json::from_str(&text)?;
34
35        Ok(response.data)
36    }
37}
38
39impl Default for Client {
40    fn default() -> Self {
41        Client::new()
42    }
43}
44
45#[cfg(test)]
46mod test {
47    use super::*;
48
49    // 9/1/2023: Online is currently broken, ignore
50    #[tokio::test]
51    #[ignore]
52    async fn it_works() {
53        let client = Client::new();
54        let user_list = client.search("KingGeorge").await.unwrap();
55        assert!(!user_list.is_empty());
56        dbg!(&user_list);
57    }
58
59    // 9/1/2023: Online is currently broken, ignore
60    #[tokio::test]
61    #[ignore]
62    async fn invalid_search() {
63        let client = Client::new();
64        let user_list = client.search("ygwdauiwgd").await.unwrap();
65        assert!(user_list.is_empty());
66        dbg!(&user_list);
67    }
68}