openmeteo-rs 1.0.0

Rust client for the Open-Meteo weather API.
Documentation
//! Seasonal forecast endpoint builder.

use reqwest::Url;

use super::url::{
    QueryParam, build_endpoint_url, push_api_param, push_api_values, push_display_param,
    push_float_param,
};
use super::validation::{validate_at_most, validate_coordinates, validate_optional_solar_angle};
use crate::response::decode_forecast_json;
use crate::units::{
    CellSelection, PrecipitationUnit, TemperatureUnit, TimeFormat, Timezone, WindSpeedUnit,
};
use crate::variables::{DailyVar, SeasonalModel, SeasonalMonthlyVar};
use crate::{Client, Error, Result, SeasonalResponse};

const MAX_FORECAST_DAYS: u8 = 210;
const MAX_PAST_DAYS: u8 = 92;

/// Builder for the `/v1/seasonal` endpoint.
#[derive(Debug)]
#[must_use = "seasonal builders do nothing until `.send().await` is called"]
pub struct SeasonalBuilder<'a> {
    client: &'a Client,
    latitude: f64,
    longitude: f64,
    daily: Vec<DailyVar>,
    monthly: Vec<SeasonalMonthlyVar>,
    models: Vec<SeasonalModel>,
    temperature_unit: Option<TemperatureUnit>,
    wind_speed_unit: Option<WindSpeedUnit>,
    precipitation_unit: Option<PrecipitationUnit>,
    timeformat: Option<TimeFormat>,
    timezone: Option<Timezone>,
    past_days: Option<u8>,
    forecast_days: Option<u8>,
    cell_selection: Option<CellSelection>,
    elevation: Option<f64>,
    tilt: Option<f32>,
    azimuth: Option<f32>,
}

impl<'a> SeasonalBuilder<'a> {
    pub(crate) fn new(client: &'a Client, latitude: f64, longitude: f64) -> Self {
        Self {
            client,
            latitude,
            longitude,
            daily: Vec::new(),
            monthly: Vec::new(),
            models: Vec::new(),
            temperature_unit: None,
            wind_speed_unit: None,
            precipitation_unit: None,
            timeformat: None,
            timezone: None,
            past_days: None,
            forecast_days: None,
            cell_selection: None,
            elevation: None,
            tilt: None,
            azimuth: None,
        }
    }

    /// Adds daily seasonal variables to the request.
    pub fn daily<I>(mut self, variables: I) -> Self
    where
        I: IntoIterator<Item = DailyVar>,
    {
        self.daily.extend(variables);
        self
    }

    /// Adds monthly seasonal variables to the request.
    pub fn monthly<I>(mut self, variables: I) -> Self
    where
        I: IntoIterator<Item = SeasonalMonthlyVar>,
    {
        self.monthly.extend(variables);
        self
    }

    /// Pins one or more seasonal models.
    pub fn models<I>(mut self, models: I) -> Self
    where
        I: IntoIterator<Item = SeasonalModel>,
    {
        self.models.extend(models);
        self
    }

    /// Sets the response temperature unit.
    pub fn temperature_unit(mut self, unit: TemperatureUnit) -> Self {
        self.temperature_unit = Some(unit);
        self
    }

    /// Sets the response wind-speed unit.
    pub fn wind_speed_unit(mut self, unit: WindSpeedUnit) -> Self {
        self.wind_speed_unit = Some(unit);
        self
    }

    /// Sets the response precipitation unit.
    pub fn precipitation_unit(mut self, unit: PrecipitationUnit) -> Self {
        self.precipitation_unit = Some(unit);
        self
    }

    /// Sets the response timestamp format.
    pub fn timeformat(mut self, format: TimeFormat) -> Self {
        self.timeformat = Some(format);
        self
    }

    /// Sets the response timezone.
    pub fn timezone(mut self, timezone: Timezone) -> Self {
        self.timezone = Some(timezone);
        self
    }

    /// Requests a number of past days.
    pub fn past_days(mut self, days: u8) -> Self {
        self.past_days = Some(days);
        self
    }

    /// Requests a number of forecast days.
    pub fn forecast_days(mut self, days: u8) -> Self {
        self.forecast_days = Some(days);
        self
    }

    /// Sets grid-cell selection.
    pub fn cell_selection(mut self, selection: CellSelection) -> Self {
        self.cell_selection = Some(selection);
        self
    }

    /// Overrides the elevation used for downscaling.
    pub fn elevation(mut self, meters: f64) -> Self {
        self.elevation = Some(meters);
        self
    }

    /// Sets panel tilt for tilted irradiance variables.
    pub fn tilt(mut self, degrees: f32) -> Self {
        self.tilt = Some(degrees);
        self
    }

    /// Sets panel azimuth for tilted irradiance variables.
    pub fn azimuth(mut self, degrees: f32) -> Self {
        self.azimuth = Some(degrees);
        self
    }

    /// Sends the request and decodes the JSON seasonal response.
    pub async fn send(self) -> Result<SeasonalResponse> {
        let url = self.build_url()?;
        let body = self.client.execute(self.client.http.get(url)).await?;
        decode_forecast_json(&body)
    }

    pub(crate) fn build_url(&self) -> Result<Url> {
        self.validate()?;

        let mut params: Vec<QueryParam> = vec![
            ("latitude", self.latitude.to_string()),
            ("longitude", self.longitude.to_string()),
        ];
        push_api_values(&mut params, "daily", &self.daily);
        push_api_values(&mut params, "monthly", &self.monthly);
        push_api_values(&mut params, "models", &self.models);
        push_api_param(
            &mut params,
            "temperature_unit",
            self.temperature_unit.as_ref(),
        );
        push_api_param(
            &mut params,
            "wind_speed_unit",
            self.wind_speed_unit.as_ref(),
        );
        push_api_param(
            &mut params,
            "precipitation_unit",
            self.precipitation_unit.as_ref(),
        );
        push_api_param(&mut params, "timeformat", self.timeformat.as_ref());
        push_api_param(&mut params, "timezone", self.timezone.as_ref());
        push_display_param(
            &mut params,
            "past_days",
            self.past_days.filter(|days| *days > 0),
        );
        push_display_param(&mut params, "forecast_days", self.forecast_days);
        push_api_param(&mut params, "cell_selection", self.cell_selection.as_ref());
        push_float_param(&mut params, "elevation", self.elevation);
        push_float_param(&mut params, "tilt", self.tilt.map(f64::from));
        push_float_param(&mut params, "azimuth", self.azimuth.map(f64::from));

        build_endpoint_url(
            &self.client.seasonal_base,
            "seasonal_base_url",
            "v1/seasonal",
            self.client.api_key.as_deref(),
            params,
        )
    }

    fn validate(&self) -> Result<()> {
        validate_coordinates(self.latitude, self.longitude)?;
        if self.daily.is_empty() && self.monthly.is_empty() {
            return Err(Error::InvalidParam {
                field: "variables",
                reason: "set at least one daily or monthly variable".into(),
            });
        }
        validate_at_most("past_days", self.past_days, MAX_PAST_DAYS)?;
        validate_at_most("forecast_days", self.forecast_days, MAX_FORECAST_DAYS)?;
        validate_optional_solar_angle("tilt", self.tilt, 0.0..=90.0)?;
        validate_optional_solar_angle("azimuth", self.azimuth, -180.0..=180.0)?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{DailyVar, SeasonalMonthlyVar, TemperatureUnit, Timezone};

    #[test]
    fn build_seasonal_url_with_daily_and_monthly_variables() {
        let client = Client::builder()
            .seasonal_base_url("https://example.com/seasonal?token=abc")
            .unwrap()
            .build()
            .unwrap();

        let url = client
            .seasonal(47.3769, 8.5417)
            .daily([DailyVar::Temperature2mMax])
            .monthly([SeasonalMonthlyVar::Temperature2mMean])
            .models([SeasonalModel::EcmwfSeas5])
            .timezone(Timezone::Iana("Europe/Zurich".to_owned()))
            .temperature_unit(TemperatureUnit::Fahrenheit)
            .forecast_days(1)
            .build_url()
            .unwrap();

        assert_eq!(
            url.as_str(),
            "https://example.com/seasonal/v1/seasonal?token=abc&latitude=47.3769&longitude=8.5417&daily=temperature_2m_max&monthly=temperature_2m_mean&models=ecmwf_seas5&temperature_unit=fahrenheit&timezone=Europe%2FZurich&forecast_days=1"
        );
    }

    #[test]
    fn rejects_empty_seasonal_variable_set() {
        let client = Client::new();
        let err = client.seasonal(47.3769, 8.5417).build_url().unwrap_err();

        assert!(matches!(
            err,
            Error::InvalidParam {
                field: "variables",
                ..
            }
        ));
    }
}