Skip to main content

couchbase_core/httpx/
response.rs

1/*
2 *
3 *  * Copyright (c) 2025 Couchbase, Inc.
4 *  *
5 *  * Licensed under the Apache License, Version 2.0 (the "License");
6 *  * you may not use this file except in compliance with the License.
7 *  * You may obtain a copy of the License at
8 *  *
9 *  *    http://www.apache.org/licenses/LICENSE-2.0
10 *  *
11 *  * Unless required by applicable law or agreed to in writing, software
12 *  * distributed under the License is distributed on an "AS IS" BASIS,
13 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  * See the License for the specific language governing permissions and
15 *  * limitations under the License.
16 *
17 */
18
19use bytes::Bytes;
20use futures::{Stream, TryStreamExt};
21use http::StatusCode;
22use serde::de::DeserializeOwned;
23
24use crate::httpx::error;
25use crate::httpx::error::Error;
26
27#[derive(Debug)]
28pub struct Response {
29    inner: reqwest::Response,
30}
31
32impl From<reqwest::Response> for Response {
33    fn from(value: reqwest::Response) -> Self {
34        Self { inner: value }
35    }
36}
37
38impl Response {
39    pub fn status(&self) -> StatusCode {
40        self.inner.status()
41    }
42
43    pub async fn bytes(self) -> error::Result<Bytes> {
44        self.inner.bytes().await.map_err(|e| {
45            Error::new_message_error(format!("failed to read bytes from response: {e}"))
46        })
47    }
48
49    pub fn bytes_stream(self) -> impl Stream<Item = error::Result<Bytes>> + Unpin {
50        self.inner.bytes_stream().map_err(|e| {
51            Error::new_message_error(format!("failed to read bytes stream from response: {e}"))
52        })
53    }
54
55    pub async fn json<T: DeserializeOwned>(self) -> error::Result<T> {
56        self.inner
57            .json()
58            .await
59            .map_err(|e| Error::new_decoding_error(format!("failed to decode body into json: {e}")))
60    }
61
62    pub fn url(&self) -> &str {
63        self.inner.url().as_str()
64    }
65}