use std::collections::HashMap;
use bytes::Bytes;
use reqwest::header::HeaderMap;
use serde::de::DeserializeOwned;
use super::APIError;
#[derive(Debug)]
pub struct APIResponse {
response: reqwest::Response,
}
impl APIResponse {
pub(crate) fn new(response: reqwest::Response) -> Self {
Self { response }
}
pub fn status(&self) -> u16 {
self.response.status().as_u16()
}
pub fn status_code(&self) -> reqwest::StatusCode {
self.response.status()
}
pub fn ok(&self) -> bool {
self.response.status().is_success()
}
pub fn status_text(&self) -> &str {
self.response
.status()
.canonical_reason()
.unwrap_or("Unknown")
}
pub fn headers(&self) -> &HeaderMap {
self.response.headers()
}
pub fn headers_map(&self) -> HashMap<String, String> {
self.response
.headers()
.iter()
.filter_map(|(name, value)| {
value
.to_str()
.ok()
.map(|v| (name.as_str().to_string(), v.to_string()))
})
.collect()
}
pub fn header(&self, name: &str) -> Option<&str> {
self.response
.headers()
.get(name)
.and_then(|v| v.to_str().ok())
}
pub fn url(&self) -> &str {
self.response.url().as_str()
}
pub async fn json<T: DeserializeOwned>(self) -> Result<T, APIError> {
self.response
.json()
.await
.map_err(|e| APIError::JsonError(e.to_string()))
}
pub async fn text(self) -> Result<String, APIError> {
self.response
.text()
.await
.map_err(|e| APIError::ParseError(e.to_string()))
}
pub async fn body(self) -> Result<Bytes, APIError> {
self.response
.bytes()
.await
.map_err(|e| APIError::ParseError(e.to_string()))
}
pub fn content_length(&self) -> Option<u64> {
self.response.content_length()
}
pub fn is_redirect(&self) -> bool {
self.response.status().is_redirection()
}
pub fn is_client_error(&self) -> bool {
self.response.status().is_client_error()
}
pub fn is_server_error(&self) -> bool {
self.response.status().is_server_error()
}
}
#[cfg(test)]
mod tests;