toolcraft_request/
response.rs

1use std::pin::Pin;
2
3use bytes::Bytes;
4use futures_util::{Stream, StreamExt};
5
6use crate::error::{Error, Result};
7
8pub type ByteStream = Pin<Box<dyn Stream<Item = crate::error::Result<Bytes>> + Send>>;
9pub struct Response {
10    response: reqwest::Response,
11}
12
13impl From<reqwest::Response> for Response {
14    fn from(response: reqwest::Response) -> Self {
15        Response { response }
16    }
17}
18
19impl Response {
20    /// Create a new Response wrapper.
21    pub fn new(response: reqwest::Response) -> Self {
22        Response { response }
23    }
24
25    /// Get the underlying reqwest Response.
26    pub fn inner(&self) -> &reqwest::Response {
27        &self.response
28    }
29
30    /// Get the status code of the response.
31    pub fn status(&self) -> reqwest::StatusCode {
32        self.inner().status()
33    }
34
35    /// Get the response body as a string.
36    pub async fn text(self) -> Result<String> {
37        self.response
38            .text()
39            .await
40            .map_err(Error::from)
41            .map(|s| s.to_string())
42    }
43
44    /// Get the response headers.
45    pub fn headers(&self) -> &reqwest::header::HeaderMap {
46        self.response.headers()
47    }
48
49    /// Get the response body as JSON.
50    pub async fn json<T: serde::de::DeserializeOwned>(self) -> Result<T> {
51        self.response.json::<T>().await.map_err(Error::from)
52    }
53
54    /// Get the response body as bytes.
55    pub async fn bytes(self) -> Result<Bytes> {
56        self.response.bytes().await.map_err(Error::from)
57    }
58
59    /// Get the response body as a stream of bytes.
60    pub fn bytes_stream(self) -> ByteStream {
61        let stream = self
62            .response
63            .bytes_stream()
64            .map(|chunk_result| chunk_result.map_err(Error::from));
65        Box::pin(stream)
66    }
67}