ckpool_api/
client.rs

1//! Client
2
3use bitcoin::Address;
4use reqwest::{Client, Response};
5use url::Url;
6
7use crate::builder::CKPoolClientBuilder;
8use crate::error::Error;
9use crate::response::UserStats;
10
11/// CKPool client
12#[derive(Debug, Clone)]
13pub struct CKPoolClient {
14    url: Url,
15    client: Client,
16}
17
18impl CKPoolClient {
19    /// Construct a new CKPool client instance.
20    ///
21    /// # Example
22    ///
23    /// ```rust,no_run
24    /// use ckpool_api::prelude::*;
25    ///
26    /// let url: Url = Url::parse("https://solo.braiins.com").unwrap();
27    /// let client = CKPoolClient::new(url);
28    /// # let _client = client;
29    /// ```
30    #[inline]
31    pub fn new(url: Url) -> Self {
32        Self::from_client(url, Client::new())
33    }
34
35    /// Construct a client builder
36    #[inline]
37    pub fn builder(url: Url) -> CKPoolClientBuilder {
38        CKPoolClientBuilder::new(url)
39    }
40
41    /// Construct new with a custom reqwest [`Client`].
42    #[inline]
43    pub fn from_client(url: Url, client: Client) -> Self {
44        Self { client, url }
45    }
46
47    /// Get user stats.
48    pub async fn user_stats(&self, address: &Address) -> Result<UserStats, Error> {
49        let url: Url = self
50            .url
51            .join("/users/")?
52            .join(address.to_string().as_str())?;
53        let response: Response = self.client.get(url).send().await?;
54
55        match response.error_for_status() {
56            Ok(res) => Ok(res.json().await?),
57            Err(err) => match err.status() {
58                Some(reqwest::StatusCode::NOT_FOUND) => Err(Error::UserNotFound),
59                _ => Err(Error::from(err)),
60            },
61        }
62    }
63}