use reqwest::{
self,
header::{
HeaderMap,
HeaderValue,
},
Client,
};
use crate::station::{
Station,
StationAvailability,
StationAvailabilityContainer,
StationContainer
};
use crate::error::ApiResult;
const API_BASE: &str = "https://oslobysykkel.no/api/v1";
fn url_for(endpoint: &str) -> String {
[API_BASE, endpoint].join("/")
}
pub struct Api {
client: reqwest::Client,
}
impl Api {
pub fn new(api_key: String) -> ApiResult<Api> {
let mut hdrs = HeaderMap::new();
hdrs.insert("client-identifier", HeaderValue::from_str(&api_key)?);
let client = Client::builder()
.default_headers(hdrs)
.build()?;
Ok(Api { client })
}
pub fn stations(&self) -> ApiResult<Vec<Station>> {
let response_json = self.get("stations")?;
let v: StationContainer = serde_json::from_str(&response_json)?;
Ok(v.stations)
}
pub fn station_availability(&self) -> ApiResult<Vec<StationAvailability>> {
let response_json = self.get("stations/availability")?;
let v: StationAvailabilityContainer = serde_json::from_str(&response_json)?;
Ok(v.stations)
}
fn get(&self, path: &str) -> ApiResult<String> {
self.client
.get(&url_for(path))
.send()?
.error_for_status()?
.text()
.map_err(crate::error::Error::ReqwestError)
}
}