weatherstat/src/weather.rs

71 lines
1.7 KiB
Rust
Raw Normal View History

use crate::rocket::futures::TryFutureExt;
use serde::Deserialize;
use std::env;
#[derive(Debug, Deserialize)]
struct APIResponseWeather {
main: String,
description: String,
}
#[derive(Debug, Deserialize)]
struct APIResponseMain {
temp: f32,
feels_like: f32,
humidity: u32,
pressure: u32,
}
#[derive(Debug, Deserialize)]
struct APIResponse {
weather: Vec<APIResponseWeather>,
main: APIResponseMain,
}
#[derive(Debug)]
pub enum WeatherSummary {
Clear(i32),
Drizzle(i32),
Rain(i32),
Snow(i32),
Cloudy(i32),
Thunderstorm(i32),
Other(i32, String),
}
impl From<APIResponse> for WeatherSummary {
fn from(resp: APIResponse) -> Self {
let temp = resp.main.temp as i32;
match resp.weather[0].main.as_ref() {
"Thunderstorm" => Self::Thunderstorm(temp),
"Drizzle" => Self::Drizzle(temp),
"Rain" => Self::Rain(temp),
"Snow" => Self::Snow(temp),
"Clear" => Self::Clear(temp),
"Clouds" => Self::Cloudy(temp),
_ => Self::Other(temp, resp.weather[0].description.clone()),
}
}
}
pub async fn get_summary(loc: &str) -> Result<WeatherSummary, String> {
let api_key =
env::var("OPEN_WEATHERMAP_API_KEY").expect("could not load OPEN_WEATHERMAP_API_KEY");
let url = format!(
"https://api.openweathermap.org/data/2.5/weather?q={}&appid={}&units=metric",
loc, api_key
);
println!("Got URL: {}", &url);
let body = reqwest::get(&url)
.map_err(|e| e.to_string())
.await?
.json::<APIResponse>()
.map_err(|e| e.to_string())
.await?;
Ok(body.into())
}