toolcraft_request/
response.rs1use 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 pub fn new(response: reqwest::Response) -> Self {
22 Response { response }
23 }
24
25 pub fn inner(&self) -> &reqwest::Response {
27 &self.response
28 }
29
30 pub fn status(&self) -> reqwest::StatusCode {
32 self.inner().status()
33 }
34
35 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 pub fn headers(&self) -> &reqwest::header::HeaderMap {
46 self.response.headers()
47 }
48
49 pub async fn json<T: serde::de::DeserializeOwned>(self) -> Result<T> {
51 self.response.json::<T>().await.map_err(Error::from)
52 }
53
54 pub async fn bytes(self) -> Result<Bytes> {
56 self.response.bytes().await.map_err(Error::from)
57 }
58
59 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}