Skip to content

Commit dab89c3

Browse files
committed
Expose bytes to the Response object
This patch exposes the `Response::bytes`, which is basically a wrapper on reqwest::Response::bytes().
1 parent 82d32de commit dab89c3

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

elasticsearch/src/http/response.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use crate::{
2121
error::Error as ClientError,
2222
http::{headers::HeaderMap, Method, StatusCode, Url},
2323
};
24+
use bytes::Bytes;
2425
use serde::{
2526
de,
2627
de::{DeserializeOwned, MapAccess, Visitor},
@@ -128,6 +129,14 @@ impl Response {
128129
Ok(body)
129130
}
130131

132+
/// Asynchronously reads the response body as bytes
133+
///
134+
/// Reading the response body consumes `self`
135+
pub async fn bytes(self) -> Result<Bytes, ClientError> {
136+
let bytes: Bytes = self.response.bytes().await?;
137+
Ok(bytes)
138+
}
139+
131140
/// Gets the request URL
132141
pub fn url(&self) -> &Url {
133142
self.response.url()

elasticsearch/tests/client.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ use elasticsearch::{
3232
};
3333

3434
use crate::common::client::index_documents;
35+
use bytes::Bytes;
3536
use hyper::Method;
3637
use serde_json::{json, Value};
3738
use std::time::Duration;
@@ -309,6 +310,33 @@ async fn search_with_no_body() -> Result<(), failure::Error> {
309310
Ok(())
310311
}
311312

313+
#[tokio::test]
314+
async fn read_response_as_bytes() -> Result<(), failure::Error> {
315+
let client = client::create_default();
316+
let _ = index_documents(&client).await?;
317+
let response = client
318+
.search(SearchParts::None)
319+
.pretty(true)
320+
.q("title:Elasticsearch")
321+
.send()
322+
.await?;
323+
324+
assert_eq!(response.status_code(), StatusCode::OK);
325+
assert_eq!(response.method(), elasticsearch::http::Method::Get);
326+
327+
let response: Bytes = response.bytes().await?;
328+
329+
let json: Value = serde_json::from_slice(&response).unwrap();
330+
331+
assert!(json["took"].as_i64().is_some());
332+
333+
for hit in json["hits"]["hits"].as_array().unwrap() {
334+
assert!(hit["_source"]["title"].as_str().is_some());
335+
}
336+
337+
Ok(())
338+
}
339+
312340
#[tokio::test]
313341
async fn cat_health_format_json() -> Result<(), failure::Error> {
314342
let client = client::create_default();

0 commit comments

Comments
 (0)