Modularize the owm_api25 library

- Add separate modules for weather & forecast calls
This commit is contained in:
Candifloss 2025-09-19 18:19:46 +05:30
parent 9e8c1e6029
commit d45ad9bad5
5 changed files with 85 additions and 34 deletions

View File

@ -29,6 +29,14 @@ fn default_lang() -> String {
}
impl Config {
/// Load configuration from `~/.config/candywidgets/openweathermap.toml`.
///
/// # Errors
///
/// Returns an error if:
/// - `$XDG_CONFIG_HOME` (or `~/.config`) cannot be determined,
/// - the file cannot be read,
/// - or the TOML cannot be parsed.
pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
let mut path = dirs::config_dir().ok_or("No config dir found")?;
path.push("candywidgets/openweathermap.toml");
@ -39,6 +47,12 @@ impl Config {
Ok(toml::from_str(&toml_str)?)
}
/// Build a query URL for the `OpenWeatherMap` API v2.5.
///
/// # Errors
///
/// Returns an error if no valid location parameter is set
/// (`city_id`, `city_name`, `lat`+`lon`, or `zip`).
pub fn build_url(&self) -> Result<String, String> {
let base = "https://api.openweathermap.org/data/2.5/weather";

31
owm_api25/src/forecast.rs Normal file
View File

@ -0,0 +1,31 @@
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct ForecastWeather {
pub id: u32,
pub main: String,
pub description: String,
pub icon: String,
}
#[derive(Debug, Deserialize)]
pub struct ForecastMain {
pub temp: f32,
pub pressure: f32,
pub humidity: u8,
}
#[derive(Debug, Deserialize)]
pub struct ForecastEntry {
pub dt: u64,
pub main: ForecastMain,
pub weather: Vec<ForecastWeather>,
pub dt_txt: String,
}
#[derive(Debug, Deserialize)]
pub struct ForecastResponse {
pub cod: String,
pub cnt: u32,
pub list: Vec<ForecastEntry>,
}

View File

@ -1,27 +1,3 @@
pub mod config;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Weather {
pub main: String,
pub icon: String,
}
#[derive(Debug, Deserialize)]
pub struct Main {
pub temp: f32,
}
#[derive(Debug, Deserialize)]
pub struct Sys {
pub country: String,
}
#[derive(Debug, Deserialize)]
pub struct WeatherResponse {
pub name: String,
pub sys: Sys,
pub weather: Vec<Weather>,
pub main: Main,
}
pub mod forecast;
pub mod weather;

30
owm_api25/src/weather.rs Normal file
View File

@ -0,0 +1,30 @@
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Weather {
pub main: String,
pub icon: String,
pub description: String,
}
#[derive(Debug, Deserialize)]
pub struct Main {
pub temp: f32,
pub pressure: u32,
pub humidity: u8,
}
#[derive(Debug, Deserialize)]
pub struct Sys {
pub country: String,
pub sunrise: u64,
pub sunset: u64,
}
#[derive(Debug, Deserialize)]
pub struct WeatherResponse {
pub name: String,
pub sys: Sys,
pub weather: Vec<Weather>,
pub main: Main,
}

View File

@ -1,4 +1,4 @@
use owm_api25::{WeatherResponse, config::Config};
use owm_api25::{config::Config, weather::WeatherResponse};
use reqwest::blocking;
fn main() -> Result<(), Box<dyn std::error::Error>> {