use serde::de::DeserializeOwned;
use crate::error::HttpError;
pub type Response<R, E = HttpError> = Result<R, E>;
#[derive(Debug)]
pub struct RawResponse {
status: u16,
inner: reqwest::Response,
}
impl RawResponse {
pub(crate) fn new(response: reqwest::Response) -> Self {
Self {
status: response.status().as_u16(),
inner: response,
}
}
pub fn status(&self) -> u16 {
self.status
}
pub fn is_success(&self) -> bool {
(200..300).contains(&self.status)
}
pub fn is_client_error(&self) -> bool {
(400..500).contains(&self.status)
}
pub fn is_server_error(&self) -> bool {
(500..600).contains(&self.status)
}
pub async fn text(self) -> Response<String> {
self.inner.text().await.map_err(HttpError::from)
}
pub async fn json<T: DeserializeOwned>(self) -> Response<T> {
self.inner.json().await.map_err(HttpError::from)
}
pub async fn bytes(self) -> Response<Vec<u8>> {
self.inner
.bytes()
.await
.map(|b| b.to_vec())
.map_err(HttpError::from)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_response_type_is_result() {
let success: Response<i32> = Ok(42);
assert!(success.is_ok());
assert!(matches!(success, Ok(42)));
let error: Response<i32> = Err(HttpError::Timeout);
assert!(error.is_err());
assert!(matches!(error, Err(HttpError::Timeout)));
}
}