#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![forbid(unsafe_code)]
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
Network(reqwest::Error),
ParseJson(serde_json::Error)
}
pub async fn fetch(url: &str) -> Result<String> {
match reqwest::get(url).await {
Ok(response) => match response.text().await {
Ok(data) => Ok(data),
Err(error) => Err(Error::Network(error))
},
Err(error) => Err(Error::Network(error))
}
}
pub fn from_json<T>(json: &str) -> Result<T>
where T: serde::de::DeserializeOwned {
match serde_json::from_str::<T>(json) {
Ok(data_struct) => Ok(data_struct),
Err(error) => Err(Error::ParseJson(error))
}
}
#[cfg(test)]
mod tests {
use super::*;
static TEST_API: &str = "https://random-word-api.herokuapp.com/word";
#[tokio::test(flavor = "multi_thread")]
async fn fetch_api() {
let result = fetch(TEST_API).await;
assert!(result.is_ok());
}
#[tokio::test(flavor = "multi_thread")]
async fn deserialize_string() {
let result = from_json::<Vec<String>>(r#"["1","2","3"]"#);
assert!(result.is_ok());
}
}