dns-wrapper 0.1.6

An API wrapper for Diplomacy and Strife
Documentation
use serde_json::Value;
use std::collections::HashMap;
use crate::api::ApiKey;

/// Struct for the output of different resources of your nation
#[derive(Debug)]
pub struct NationResources {
    pub nation: String,
    pub money: f64,
    pub production: f64,
    pub minerals: f64,
    pub uranium: f64,
    pub rare_metals: f64,
    pub fuel: f64,
    pub political_power: f64,
}

/// Function to fetch nation resources from the API
/// Params:
/// nation_id: i32 | gets the output of the user with the given nation id
pub async fn fetch_output(nation_id: i32) -> Result<NationResources, Box<dyn std::error::Error>> {
    let api_key = ApiKey::get_apikey().ok_or("API key not set")?;
    let url = format!(
        "https://diplomacyandstrifeapi.com/api/nation?APICode={}&NationId={}",
        api_key,
        nation_id,
    );

    let response = reqwest::get(&url)
        .await?
        .json::<Vec<HashMap<String, Value>>>()
        .await?;

    if let Some(user_data) = response
        .into_iter()
        .find(|entry| entry["NationId"] == nation_id)
    {
        Ok(NationResources {
            nation: user_data["NationName"].as_str().unwrap_or("").to_string(),
            money: user_data["CashOutput"].as_f64().unwrap_or(0.0),
            production: user_data["ProductionOutput"].as_f64().unwrap_or(0.0),
            minerals: user_data["MineralOutput"].as_f64().unwrap_or(0.0),
            uranium: user_data["UraniumOutput"].as_f64().unwrap_or(0.0),
            rare_metals: user_data["RareMetalOutput"].as_f64().unwrap_or(0.0),
            fuel: user_data["FuelOutput"].as_f64().unwrap_or(0.0),
            political_power: user_data["PoliticalPowerOutput"].as_f64().unwrap_or(0.0),
        })
    } else {
        Err("Nation not found".into())
    }
}