mod api;
pub use api::*;
mod models;
pub use models::*;
mod lang;
pub use lang::Language;
mod query;
pub use query::Query;
pub use chrono;
use ureq::{Agent, AgentBuilder};
use std::fmt::Display;
#[derive(Debug, Clone)]
pub struct Client {
pub(crate) api_key: String,
pub(crate) agent: Agent,
pub(crate) https: bool
}
impl Client {
pub fn new(api_key: &str, https: bool) -> Self {
let user_agent = format!(
"{name} ({repo} {version})",
name = env!("CARGO_PKG_NAME"),
repo = env!("CARGO_PKG_REPOSITORY"),
version = env!("CARGO_PKG_VERSION"),
);
let agent = AgentBuilder::new()
.user_agent(&user_agent)
.https_only(https)
.build();
Self {
api_key: api_key.to_string(),
agent,
https
}
}
pub fn forecast<Tz: chrono::TimeZone>(&self) -> ForecastApi<Tz>
where
Tz::Offset: Display
{
ForecastApi::<Tz>::new(&self)
}
pub fn future<Tz: chrono::TimeZone>(&self) -> FutureApi<Tz>
where
Tz::Offset: Display
{
FutureApi::new(&self)
}
pub fn history<Tz: chrono::TimeZone>(&self) -> HistoryApi<Tz>
where
Tz::Offset: Display
{
HistoryApi::<Tz>::new(&self)
}
pub fn realtime(&self) -> RealtimeApi {
RealtimeApi::new(&self)
}
pub fn search(&self) -> SearchApi {
SearchApi::new(&self)
}
pub fn conditions(&self) -> Result<Vec<Condition>, ureq::Error> {
Ok(self.agent.get("https://www.weatherapi.com/docs/weather_conditions.json").call()?.into_json()?)
}
}
#[cfg(test)]
mod tests {
use crate::*;
use chrono::{Utc, TimeZone};
fn get_client() -> Client {
let api_key = option_env!("API_KEY").unwrap();
Client::new(api_key, true)
}
#[test]
fn forecast() {
let client = get_client();
let result = client.forecast()
.query(Query::Ip(None))
.dt(Utc.ymd(2022, 08, 21).and_hms(0, 0, 0))
.lang(Language::Spanish)
.call();
assert!(result.is_ok())
}
#[test]
fn future() {
let client = get_client();
let result = client.future()
.query(Query::Ip(None))
.dt(Utc.ymd(2022, 09, 21).and_hms(0, 0, 0))
.lang(Language::Spanish)
.call();
assert!(result.is_ok())
}
#[test]
fn history() {
let client = get_client();
let result = client.history()
.query(Query::Ip(None))
.dt(Utc.ymd(2022, 07, 21).and_hms(0, 0, 0))
.hour()
.call();
assert!(result.is_ok())
}
#[test]
fn realtime() {
let client = get_client();
let result = client.realtime()
.query(Query::Ip(None))
.lang(Language::Spanish)
.call();
assert!(result.is_ok())
}
#[test]
fn search() {
let client = get_client();
let result = client.search().query(Query::Ip(None)).call();
assert!(result.is_ok())
}
#[test]
fn lang() {
let l = Language::new("bg").unwrap();
assert_eq!(Language::Bulgarian, l)
}
#[test]
fn it_works() {
let result = 2 + 2;
assert_eq!(result, 4);
}
}