brawl-rs 0.1.0

A Rust wrapper for the Brawl Stars API
Documentation
//! HTTP client for communicating with the Brawl Stars API.
//!
//! This module provides the main [`BrawlClient`] type used to make authenticated requests
//! to the Brawl Stars API endpoints.

pub mod endpoints;

use crate::client::endpoints::{Endpoint, BASE_URL};
use crate::errors::{ApiError, BrawlError};
use reqwest::Client;

/// Main client for interacting with the Brawl Stars API.
///
/// The [`BrawlClient`] handles all HTTP communication with the Brawl Stars API,
/// including authentication, error handling, and JSON deserialization.
///
/// # Examples
///
/// ```no_run
/// use brawl_rs::prelude::*;
///
/// let client = BrawlClient::new("your_api_token_here");
/// ```
///
pub struct BrawlClient {
    pub(crate) http: Client,
    pub(crate) api_key: String,
}

impl BrawlClient {
    /// Creates a new [`BrawlClient`] with the provided API key.
    ///
    /// The API key can be obtained from the [Brawl Stars Developer Portal](https://developer.brawlstars.com/).
    ///
    /// # Arguments
    ///
    /// * `api_key` - Your Brawl Stars API token for authentication
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use brawl_rs::prelude::*;
    ///
    /// let client = BrawlClient::new("eyJ0eXAiOiJKV1QiLCJhbGci...");
    /// ```
    pub fn new(api_key: impl Into<String>) -> Self {
        let client = Client::new();
        Self {
            http: client,
            api_key: api_key.into(),
        }
    }

    /// Fetches data from a Brawl Stars API endpoint and deserializes it.
    ///
    /// # Errors
    ///
    /// Returns [`BrawlError`] if:
    /// - Network communication fails
    /// - The API returns an error status
    /// - JSON deserialization fails
    ///
    pub(crate) async fn fetch<T>(&self, endpoint: Endpoint) -> Result<T, BrawlError>
    where
        T: serde::de::DeserializeOwned,
    {
        let url = format!("{}{}", BASE_URL, endpoint);

        let response = self
            .http
            .get(url)
            .bearer_auth(&self.api_key)
            .header(
                "User-Agent",
                format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")),
            )
            .send()
            .await
            .map_err(BrawlError::Network)?;

        let status = response.status();

        if status.is_success() {
            response
                .json::<T>()
                .await
                .map_err(BrawlError::Serialization)
        } else {
            let err_body = response
                .json::<ApiError>()
                .await
                .map_err(BrawlError::Serialization)?;

            Err(BrawlError::Api(err_body))
        }
    }
}