use std::{collections::HashMap, fmt::Display, str::FromStr, time::{SystemTime, UNIX_EPOCH}};
use reqwest::Client;
use thiserror::Error;
const ENDPOINT: &str = "https://status.archlinux.org/api";
#[derive(Debug, Error)]
pub enum RequestError {
#[error("HTTP error: {0}")]
HttpError(#[from] reqwest::Error),
#[error("Date error: {0}")]
Date(String),
#[error("Unexpected error: {0}")]
Other(String),
#[error("Parsing JSON error: {0}")]
ParsingJSON(String)
}
pub struct RequestWrapper {
client: Client
}
impl RequestWrapper {
pub fn with_headers(headers: HashMap<&str, &str>) -> Self {
Self::new(Some(headers))
}
pub fn default() -> Self {
Self::new(None)
}
pub async fn get<T>(&self, path: T) -> Result<String, RequestError>
where
T: AsRef<str> + Display
{
let url = format!("{ENDPOINT}{}&_={}", &path, self.cache_buster());
let resp = self.client.get(&url).send().await?;
let body = resp.text().await?;
Ok(body)
}
fn new(default_headers: Option<HashMap<&str, &str>>) -> Self {
let mut headers = reqwest::header::HeaderMap::new();
if let Some(map) = default_headers {
for (key, value) in map {
headers.insert(
reqwest::header::HeaderName::from_str(key).unwrap(),
reqwest::header::HeaderValue::from_str(value).unwrap()
);
}
}
let client = Client::builder()
.default_headers(headers)
.build()
.unwrap();
Self { client }
}
fn cache_buster(&self) -> u128 {
let now = SystemTime::now();
now.duration_since(UNIX_EPOCH)
.expect("Time went backwards")
.as_millis()
}
}