dns_wrapper/api/
output.rs

1use serde_json::Value;
2use std::collections::HashMap;
3use crate::api::ApiKey;
4
5/// Struct for the output of different resources of your nation
6#[derive(Debug)]
7pub struct NationResources {
8    pub nation: String,
9    pub money: f64,
10    pub production: f64,
11    pub minerals: f64,
12    pub uranium: f64,
13    pub rare_metals: f64,
14    pub fuel: f64,
15    pub political_power: f64,
16}
17
18/// Function to fetch nation resources from the API
19/// Params:
20/// nation_id: i32 | gets the output of the user with the given nation id
21pub async fn fetch_output(nation_id: i32) -> Result<NationResources, Box<dyn std::error::Error>> {
22    let api_key = ApiKey::get_apikey().ok_or("API key not set")?;
23    let url = format!(
24        "https://diplomacyandstrifeapi.com/api/nation?APICode={}&NationId={}",
25        api_key,
26        nation_id,
27    );
28
29    let response = reqwest::get(&url)
30        .await?
31        .json::<Vec<HashMap<String, Value>>>()
32        .await?;
33
34    if let Some(user_data) = response
35        .into_iter()
36        .find(|entry| entry["NationId"] == nation_id)
37    {
38        Ok(NationResources {
39            nation: user_data["NationName"].as_str().unwrap_or("").to_string(),
40            money: user_data["CashOutput"].as_f64().unwrap_or(0.0),
41            production: user_data["ProductionOutput"].as_f64().unwrap_or(0.0),
42            minerals: user_data["MineralOutput"].as_f64().unwrap_or(0.0),
43            uranium: user_data["UraniumOutput"].as_f64().unwrap_or(0.0),
44            rare_metals: user_data["RareMetalOutput"].as_f64().unwrap_or(0.0),
45            fuel: user_data["FuelOutput"].as_f64().unwrap_or(0.0),
46            political_power: user_data["PoliticalPowerOutput"].as_f64().unwrap_or(0.0),
47        })
48    } else {
49        Err("Nation not found".into())
50    }
51}