1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
//! # Aspiration
//! Unofficial library for [Holiday API](https://holidayapi.com) written in Rust. This repo implements interface for original HolidayAPI endpoints seen [here](https://holidayapi.com/docs).
//! ## Acknowledgments
//! This project is heavily inspired by [holidayapi-node](https://github.com/holidayapi/holidayapi-node) and [holiday-api-rust](https://github.com/guibranco/holiday-api-rust) repositories.
extern crate log;
mod requests;
mod responses;
use requests::{
CountriesRequest, HolidaysRequest, LanguagesRequest, WorkdayRequest, WorkdaysRequest,
};
use serde_json::{Value, Value::Object};
use std::{collections::HashMap, error::Error, fmt};
use regex::Regex;
pub use reqwest::Response;
use reqwest::{StatusCode, Url};
#[derive(Debug, Clone)]
pub struct HolidayAPI {
base_url: String,
key: String,
}
#[derive(Debug)]
pub enum HolidayAPIError {
InvalidKeyFormat(String),
InvalidOrExpiredKey(String),
InvalidVersion(String),
RequestError(reqwest::Error, String),
}
#[derive(strum_macros::Display)]
pub enum Endpoint {
Countries,
Holidays,
Languages,
Workday,
Workdays,
}
impl fmt::Display for HolidayAPIError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
HolidayAPIError::InvalidKeyFormat(key) => write!(f, "Invalid key: {}", key),
HolidayAPIError::InvalidVersion(version) => write!(f, "Invalid version: {}", version),
HolidayAPIError::InvalidOrExpiredKey(key) => {
write!(f, "Invalid or expired key: {}", key)
}
HolidayAPIError::RequestError(req, err) => {
write!(
f,
"{} ({}): {}\nRaw url: '{}'",
req.status().unwrap().canonical_reason().unwrap(),
req.status().unwrap(),
err,
req.url().unwrap(),
)
}
}
}
}
impl Error for HolidayAPIError {}
impl HolidayAPI {
pub fn is_valid_key(key: &str) -> Result<(), HolidayAPIError> {
let uuid_regex =
Regex::new(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
.expect("Regex is correct");
if uuid_regex.is_match(key) {
Ok(())
} else {
Err(HolidayAPIError::InvalidKeyFormat(key.into()))
}
}
pub fn is_valid_version(version: &i32) -> Result<(), HolidayAPIError> {
let valid_versions = [1];
if !valid_versions.contains(version) {
Err(HolidayAPIError::InvalidVersion(format!(
"Invalid version: {}, please choose: {:?}",
version, valid_versions
)))
} else {
Ok(())
}
}
fn construct_api(key: &str, version: i32) -> HolidayAPI {
HolidayAPI {
base_url: format!("https://holidayapi.com/v{}/", version),
key: key.to_owned(),
}
}
/// Construct a new holiday API
///
/// # Errors
///
/// Will return an `Err` if the given key is not plausibly a valid one.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// use holidayapi_rust::HolidayAPI;
///
/// let api = HolidayAPI::new("00000000-0000-0000-0000-000000000000").unwrap();
/// ```
pub fn new(key: &str) -> Result<HolidayAPI, HolidayAPIError> {
Self::is_valid_key(key)?;
Ok(Self::construct_api(key, 1))
}
/// Construct a new holiday API
///
/// # Errors
///
/// Will return an `Err` if the given key is not plausibly a valid one. Or the api version is invalid.
/// Current valid versions: `[1]`
///
/// # Examples
///
/// Basic usage
///
/// ```
/// use holidayapi_rust::HolidayAPI;
///
/// let api = HolidayAPI::with_version("00000000-0000-0000-0000-000000000000", 1).unwrap();
/// ```
pub fn with_version(key: &str, version: i32) -> Result<HolidayAPI, HolidayAPIError> {
Self::is_valid_key(key)?;
Self::is_valid_version(&version)?;
Ok(Self::construct_api(key, version))
}
/// Make a custom request.
/// # Examples
///
/// Basic usage
///
/// ```
/// use holidayapi_rust::{ HolidayAPI, Endpoint };
/// use std::collections::HashMap;
///
/// let api = HolidayAPI::new("00000000-0000-0000-0000-000000000000").unwrap();
/// let _future = api.custom_request(Endpoint::Countries, HashMap::new());
/// ```
pub async fn custom_request(
&self,
endpoint: Endpoint,
parameters: HashMap<String, String>,
) -> Result<Response, Box<dyn Error>> {
let client = reqwest::Client::new();
let url = Url::parse(self.base_url.as_str())?;
let url = url.join(endpoint.to_string().to_ascii_lowercase().as_str())?;
let url = Url::parse_with_params(&format!("{}?key={}", url, self.key), parameters)?;
let response = client.get(url).send().await?;
match response.error_for_status_ref() {
Ok(_) => Ok(response),
Err(err) => {
let val = serde_json::from_str::<Value>(&response.text().await?)?;
let o = val.as_object();
let error = o.and_then(|o| o.get("error")).unwrap();
Err(Box::new(HolidayAPIError::RequestError(
err,
error.as_str().unwrap().into(),
)))
}
}
}
/// Generates a minimal `countries` request and returns it.
///
/// # Examples
///
/// Basic usage
/// ```
/// use holidayapi_rust::HolidayAPI;
///
/// let api = HolidayAPI::new("00000000-0000-0000-0000-000000000000").unwrap();
/// let request = api.countries();
/// ```
///
/// Adding optional parameters with builder pattern
/// ```
/// use holidayapi_rust::HolidayAPI;
///
/// let api = HolidayAPI::new("00000000-0000-0000-0000-000000000000").unwrap();
/// let specific_request = api.countries().search("united states").public();
/// ```
pub fn countries(&self) -> CountriesRequest {
CountriesRequest::new(self)
}
/// Generates a minimal `holidays` request and returns it.
///
/// # Examples
///
/// Basic usage
/// ```
/// use holidayapi_rust::HolidayAPI;
///
/// let api = HolidayAPI::new("00000000-0000-0000-0000-000000000000").unwrap();
/// let request = api.holidays("us", 2020);
/// ```
///
/// Adding optional parameters with builder pattern
/// ```
/// use holidayapi_rust::HolidayAPI;
///
/// let api = HolidayAPI::new("00000000-0000-0000-0000-000000000000").unwrap();
/// let specific_request = api.holidays("us", 2020).month(12).upcoming();
/// ```
pub fn holidays(&self, country: &str, year: i32) -> HolidaysRequest {
HolidaysRequest::new(self, country.into(), year)
}
/// Generates a minimal `workday` request and returns it.
///
/// # Examples
///
/// Basic usage
/// ```
/// use holidayapi_rust::HolidayAPI;
///
/// let api = HolidayAPI::new("00000000-0000-0000-0000-000000000000").unwrap();
/// let request = api.workday("us","YYYY-MM-DD", 100);
/// ```
pub fn workday(&self, country: &str, start: &str, days: i32) -> WorkdayRequest {
WorkdayRequest::new(self, country, start, days)
}
/// Generates a minimal `workdays` request and returns it.
///
/// # Examples
///
/// Basic usage
/// ```
/// use holidayapi_rust::HolidayAPI;
///
/// let api = HolidayAPI::new("00000000-0000-0000-0000-000000000000").unwrap();
/// let request = api.workdays("us", "YYYY-MM-DD", "YYYY-MM-DD");
/// ```
pub fn workdays(&self, country: &str, start: &str, days: &str) -> WorkdaysRequest {
WorkdaysRequest::new(self, country, start, days)
}
/// Generates a minimal `languages` request and returns it.
///
/// # Examples
///
/// Basic usage
/// ```
/// use holidayapi_rust::HolidayAPI;
///
/// let api = HolidayAPI::new("00000000-0000-0000-0000-000000000000").unwrap();
/// let request = api.languages();
/// ```
///
/// Adding optional parameters with builder pattern
/// ```
/// use holidayapi_rust::HolidayAPI;
///
/// let api = HolidayAPI::new("00000000-0000-0000-0000-000000000000").unwrap();
/// let specific_request = api.languages().search("united states");
/// ```
pub fn languages(&self) -> LanguagesRequest {
LanguagesRequest::new(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
static EXPIRED_KEY: &str = "daaaaaab-aaaa-aaaa-aaaa-2aaaada37e14";
static INVALID_KEY: &str = "invalid-key-format";
#[test]
fn test_valid_key() {
match HolidayAPI::new(EXPIRED_KEY) {
Ok(_) => assert!(true),
Err(_) => unreachable!("Should not return an error on valid key"),
}
match HolidayAPI::new(INVALID_KEY) {
Ok(_) => unreachable!("Should return an error on invalid key"),
Err(_) => assert!(true),
}
}
}