mcapi 0.3.1

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
use reqwest::header::ACCEPT;
use serde::Serialize;
use serde::de::DeserializeOwned;

use super::models::{
    BlessingEnvelope, LoginResponse, PaginatedList, SkinlibItem, SkinlibQuery, TextureDetail,
};
use super::{ACCEPT_JSON, BlessingClient, unwrap_envelope};
use crate::error::Result;

#[derive(Serialize)]
struct LoginBody<'a> {
    identification: &'a str,
    password: &'a str,
}

impl BlessingClient {
    /// Authenticates a user with email/username and password via `POST /api/auth/login`,
    /// returning a Bearer token for `client.authed(token)`.
    pub async fn login(&self, identification: &str, password: &str) -> Result<LoginResponse> {
        self.post_public_envelope(
            "/auth/login",
            &LoginBody {
                identification,
                password,
            },
        )
        .await
    }

    /// Searches or lists public textures in the skin library via `GET /skinlib/list`.
    pub async fn skinlib(&self, query: &SkinlibQuery) -> Result<PaginatedList<SkinlibItem>> {
        let url = format!("{}/skinlib/list", self.site_url);
        let resp = self
            .http
            .send_with(&url, |client, target| {
                client.get(target).header(ACCEPT, ACCEPT_JSON).query(query)
            })
            .await?;
        parse_raw_or_envelope(resp.json().await?)
    }

    /// Fetches detailed metadata for a texture via `GET /skinlib/info/{tid}`.
    pub async fn skinlib_info(&self, tid: u64) -> Result<TextureDetail> {
        let url = format!("{}/skinlib/info/{tid}", self.site_url);
        let resp = self
            .http
            .send_with(&url, |client, target| {
                client.get(target).header(ACCEPT, ACCEPT_JSON)
            })
            .await?;
        parse_raw_or_envelope(resp.json().await?)
    }
}

fn parse_raw_or_envelope<T: DeserializeOwned>(value: serde_json::Value) -> Result<T> {
    if value.get("code").and_then(|c| c.as_i64()).is_some() {
        let env: BlessingEnvelope<T> = serde_json::from_value(value)?;
        unwrap_envelope(env)
    } else {
        Ok(serde_json::from_value(value)?)
    }
}