use reqwest::Url;
use time::Date;
use super::url::{
QueryParam, build_endpoint_url, push_api_param, push_api_values, push_float_param,
};
use super::validation::{validate_coordinates, validate_ordered_range};
use crate::response::decode_forecast_json;
use crate::units::{
CellSelection, PrecipitationUnit, TemperatureUnit, TimeFormat, Timezone, WindSpeedUnit,
};
use crate::variables::{ClimateDailyVar, ClimateModel};
use crate::{Client, ClimateResponse, Error, Result};
#[derive(Debug)]
#[must_use = "climate builders do nothing until `.send().await` is called"]
pub struct ClimateBuilder<'a> {
client: &'a Client,
latitude: f64,
longitude: f64,
start_date: Date,
end_date: Date,
daily: Vec<ClimateDailyVar>,
models: Vec<ClimateModel>,
temperature_unit: Option<TemperatureUnit>,
wind_speed_unit: Option<WindSpeedUnit>,
precipitation_unit: Option<PrecipitationUnit>,
timeformat: Option<TimeFormat>,
timezone: Option<Timezone>,
cell_selection: Option<CellSelection>,
elevation: Option<f64>,
disable_bias_correction: Option<bool>,
}
impl<'a> ClimateBuilder<'a> {
pub(crate) fn new(
client: &'a Client,
latitude: f64,
longitude: f64,
start_date: Date,
end_date: Date,
) -> Self {
Self {
client,
latitude,
longitude,
start_date,
end_date,
daily: Vec::new(),
models: Vec::new(),
temperature_unit: None,
wind_speed_unit: None,
precipitation_unit: None,
timeformat: None,
timezone: None,
cell_selection: None,
elevation: None,
disable_bias_correction: None,
}
}
pub fn daily<I>(mut self, variables: I) -> Self
where
I: IntoIterator<Item = ClimateDailyVar>,
{
self.daily.extend(variables);
self
}
pub fn models<I>(mut self, models: I) -> Self
where
I: IntoIterator<Item = ClimateModel>,
{
self.models.extend(models);
self
}
pub fn temperature_unit(mut self, unit: TemperatureUnit) -> Self {
self.temperature_unit = Some(unit);
self
}
pub fn wind_speed_unit(mut self, unit: WindSpeedUnit) -> Self {
self.wind_speed_unit = Some(unit);
self
}
pub fn precipitation_unit(mut self, unit: PrecipitationUnit) -> Self {
self.precipitation_unit = Some(unit);
self
}
pub fn timeformat(mut self, format: TimeFormat) -> Self {
self.timeformat = Some(format);
self
}
pub fn timezone(mut self, timezone: Timezone) -> Self {
self.timezone = Some(timezone);
self
}
pub fn cell_selection(mut self, selection: CellSelection) -> Self {
self.cell_selection = Some(selection);
self
}
pub fn elevation(mut self, meters: f64) -> Self {
self.elevation = Some(meters);
self
}
pub fn disable_bias_correction(mut self, disabled: bool) -> Self {
self.disable_bias_correction = Some(disabled);
self
}
pub async fn send(self) -> Result<ClimateResponse> {
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()),
("start_date", self.start_date.to_string()),
("end_date", self.end_date.to_string()),
];
push_api_values(&mut params, "daily", &self.daily);
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_api_param(&mut params, "cell_selection", self.cell_selection.as_ref());
push_float_param(&mut params, "elevation", self.elevation);
if let Some(disabled) = self.disable_bias_correction {
params.push(("disable_bias_correction", disabled.to_string()));
}
build_endpoint_url(
&self.client.climate_base,
"climate_base_url",
"v1/climate",
self.client.api_key.as_deref(),
params,
)
}
fn validate(&self) -> Result<()> {
validate_coordinates(self.latitude, self.longitude)?;
if self.daily.is_empty() {
return Err(Error::InvalidParam {
field: "daily",
reason: "set at least one daily variable".into(),
});
}
validate_ordered_range(
"date_range",
Some((self.start_date, self.end_date)),
"start date must be before or equal to end date",
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ClimateDailyVar, ClimateModel, TemperatureUnit, Timezone};
use time::macros::date;
#[test]
fn build_climate_url_with_daily_variables() {
let client = Client::builder()
.climate_base_url("https://example.com/climate?token=abc")
.unwrap()
.build()
.unwrap();
let url = client
.climate(
47.3769,
8.5417,
date!(2025 - 01 - 01),
date!(2025 - 01 - 02),
)
.daily([
ClimateDailyVar::Temperature2mMax,
ClimateDailyVar::PrecipitationSum,
])
.models([ClimateModel::CmccCm2Vhr4])
.timezone(Timezone::Iana("Europe/Zurich".to_owned()))
.temperature_unit(TemperatureUnit::Fahrenheit)
.disable_bias_correction(true)
.build_url()
.unwrap();
assert_eq!(
url.as_str(),
"https://example.com/climate/v1/climate?token=abc&latitude=47.3769&longitude=8.5417&start_date=2025-01-01&end_date=2025-01-02&daily=temperature_2m_max%2Cprecipitation_sum&models=CMCC_CM2_VHR4&temperature_unit=fahrenheit&timezone=Europe%2FZurich&disable_bias_correction=true"
);
}
#[test]
fn rejects_empty_climate_variable_set() {
let client = Client::new();
let err = client
.climate(
47.3769,
8.5417,
date!(2025 - 01 - 01),
date!(2025 - 01 - 02),
)
.build_url()
.unwrap_err();
assert!(matches!(err, Error::InvalidParam { field: "daily", .. }));
}
#[test]
fn rejects_reversed_climate_date_range() {
let client = Client::new();
let err = client
.climate(
47.3769,
8.5417,
date!(2025 - 01 - 02),
date!(2025 - 01 - 01),
)
.daily([ClimateDailyVar::Temperature2mMax])
.build_url()
.unwrap_err();
assert!(matches!(
err,
Error::InvalidParam {
field: "date_range",
..
}
));
}
}