Skip to content

Commit f2ee7c4

Browse files
authored
Merge pull request #37 from KodrAus/feat/index-response
Refactor Parsing
2 parents d456b8b + 6631b13 commit f2ee7c4

24 files changed

+611
-421
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
[package]
22
authors = ["Stephan Buys <stephan.buys@panoptix.co.za>"]
33
name = "elastic_responses"
4-
version = "0.7.2"
4+
version = "0.8.0"
55
license = "MIT/Apache-2.0"
66
description = "Parses search results from Elasticsearch and presents results using convenient iterators."
77
documentation = "https://docs.rs/elastic_responses"

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Query your Elasticsearch Cluster, then iterate through the results:
3232
let mut res = client.elastic_req(&params, SearchRequest::for_index("_all", body)).unwrap();
3333

3434
// Parse body to JSON
35-
let body_as_json: SearchResponse = res.json().unwrap();
35+
let body_as_json = parse::<SearchResponse>().from_reader(res.status().to_u16(), res).unwrap();
3636

3737
// Use hits() or aggs() iterators
3838
// Hits
@@ -55,7 +55,7 @@ Bulk response operations are split by whether they succeeded or failed:
5555
let mut res = client.elastic_req(&params, BulkRequest::new(body)).unwrap();
5656

5757
// Parse body to JSON
58-
let body_as_json: BulkResponse = res.json().unwrap();
58+
let body_as_json = parse::<BulkResponse>().from_reader(res.status().to_u16(), res).unwrap();
5959

6060
// Do something with successful operations
6161
for op in body_as_json.items.ok {

samples/bulk/src/main.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ extern crate elastic_responses;
99

1010
use elastic_reqwest::ElasticClient;
1111
use elastic_reqwest::req::BulkRequest;
12-
use elastic_responses::{HttpResponse, BulkErrorsResponse};
12+
use elastic_responses::{parse, BulkErrorsResponse};
1313

1414
fn get_req() -> String {
1515
let mut bulk = String::new();
@@ -31,13 +31,10 @@ fn main() {
3131
let (client, params) = elastic_reqwest::default().unwrap();
3232

3333
// Send the request and read the response.
34-
let http_res = {
35-
let res = client.elastic_req(&params, BulkRequest::new(get_req())).unwrap();
36-
HttpResponse::from_read(res.status().to_u16(), res)
37-
};
34+
let res = client.elastic_req(&params, BulkRequest::new(get_req())).unwrap();
3835

3936
//Parse body to JSON. You could also use `BulkErrorsResponse`.
40-
let body_as_json: BulkErrorsResponse = http_res.into_response().unwrap();
37+
let body_as_json: BulkErrorsResponse = parse::<BulkErrorsResponse>().from_reader(res.status().to_u16(), res).unwrap();
4138

4239
println!("{:?}", body_as_json);
4340
}

samples/search/src/main.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ extern crate elastic_responses;
99

1010
use elastic_reqwest::{ElasticClient};
1111
use elastic_reqwest::req::SearchRequest;
12-
use elastic_responses::{HttpResponse, SearchResponse};
12+
use elastic_responses::{parse, SearchResponse};
1313

1414
fn main() {
1515

@@ -67,13 +67,10 @@ fn main() {
6767
});
6868

6969
// Send the request and read the response.
70-
let http_res = {
71-
let res = client.elastic_req(&params, SearchRequest::for_index("_all", body)).unwrap();
72-
HttpResponse::from_read(res.status().to_u16(), res)
73-
};
70+
let res = client.elastic_req(&params, SearchRequest::for_index("_all", body)).unwrap();
7471

7572
//Parse body to JSON
76-
let body_as_json: SearchResponse = http_res.into_response().unwrap();
73+
let body_as_json: SearchResponse = parse::<SearchResponse>().from_reader(res.status().to_u16(), res).unwrap();
7774

7875
//Use hits() or aggs() iterators
7976
//Hits

src/bulk.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@ use serde::de::{Deserialize, Deserializer, Visitor, Error as DeError, SeqAccess,
22
use serde_json::Value;
33
use common::Shards;
44

5-
use super::HttpResponseHead;
6-
use parse::{IsOk, ResponseBody, Unbuffered, MaybeOkResponse};
5+
use parsing::{IsOk, HttpResponseHead, ResponseBody, Unbuffered, MaybeOkResponse};
76
use error::*;
87

98
use std::cmp;
@@ -13,6 +12,8 @@ use std::error::Error;
1312

1413
type BulkError = Value;
1514

15+
type DefaultAllocatedField = String;
16+
1617
/// Response for a [bulk request](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html).
1718
///
1819
/// This type splits successful and failed bulk operations so it's easier
@@ -90,7 +91,7 @@ type BulkError = Value;
9091
/// # }
9192
/// ```
9293
#[derive(Deserialize, Debug, Clone)]
93-
pub struct BulkResponse<TIndex = String, TType = String, TId = String> {
94+
pub struct BulkResponse<TIndex = DefaultAllocatedField, TType = DefaultAllocatedField, TId = DefaultAllocatedField> {
9495
pub took: u64,
9596
errors: bool,
9697
pub items: BulkItems<TIndex, TType, TId>,
@@ -170,7 +171,7 @@ impl<TIndex, TType, TId> BulkResponse<TIndex, TType, TId> {
170171
/// ```
171172
#[derive(Deserialize, Debug, Clone)]
172173
#[serde(bound(deserialize = "TIndex: Deserialize<'de>, TType: Deserialize<'de>, TId: Deserialize<'de>"))]
173-
pub struct BulkErrorsResponse<TIndex = String, TType = String, TId = String> {
174+
pub struct BulkErrorsResponse<TIndex = DefaultAllocatedField, TType = DefaultAllocatedField, TId = DefaultAllocatedField> {
174175
pub took: u64,
175176
errors: bool,
176177
#[serde(deserialize_with = "deserialize_bulk_item_errors")]
@@ -189,7 +190,7 @@ impl<TIndex, TType, TId> BulkErrorsResponse<TIndex, TType, TId> {
189190

190191
/// A successful bulk response item.
191192
#[derive(Debug, Clone)]
192-
pub struct BulkItem<TIndex, TType, TId> {
193+
pub struct BulkItem<TIndex = DefaultAllocatedField, TType = DefaultAllocatedField, TId = DefaultAllocatedField> {
193194
pub action: BulkAction,
194195
pub index: TIndex,
195196
pub ty: TType,
@@ -202,7 +203,7 @@ pub struct BulkItem<TIndex, TType, TId> {
202203

203204
/// A failed bulk response item.
204205
#[derive(Debug, Clone)]
205-
pub struct BulkItemError<TIndex, TType, TId> {
206+
pub struct BulkItemError<TIndex = DefaultAllocatedField, TType = DefaultAllocatedField, TId = DefaultAllocatedField> {
206207
pub action: BulkAction,
207208
pub index: TIndex,
208209
pub ty: TType,

src/command.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
use parsing::{IsOk, HttpResponseHead, ResponseBody, Unbuffered, MaybeOkResponse};
2+
use error::*;
3+
4+
/// A standard command acknowledgement response.
5+
#[derive(Deserialize, Debug, Clone)]
6+
pub struct CommandResponse {
7+
pub acknowledged: bool
8+
}
9+
10+
impl IsOk for CommandResponse {
11+
fn is_ok<B: ResponseBody>(head: HttpResponseHead, body: Unbuffered<B>) -> Result<MaybeOkResponse<B>, ParseResponseError> {
12+
match head.status() {
13+
200...299 => Ok(MaybeOkResponse::ok(body)),
14+
_ => Ok(MaybeOkResponse::err(body)),
15+
}
16+
}
17+
}

src/error.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ quick_error! {
4242
description("request parse error")
4343
display("request parse error: '{}' on line: {}, col: {}", reason, line, col)
4444
}
45+
MapperParsing { reason: String } {
46+
description("mapper parse error")
47+
display("mapper parse error: '{}'", reason)
48+
}
4549
ActionRequestValidation { reason: String }
4650
Other(v: Map<String, Value>) {
4751
description("error response from Elasticsearch")
@@ -111,6 +115,13 @@ impl From<Map<String, Value>> for ApiError {
111115
reason: reason.into(),
112116
}
113117
}
118+
"mapper_parsing_exception" => {
119+
let reason = error_key!(obj[reason]: |v| v.as_str());
120+
121+
ApiError::MapperParsing {
122+
reason: reason.into(),
123+
}
124+
}
114125
"action_request_validation_exception" => {
115126
let reason = error_key!(obj[reason]: |v| v.as_str());
116127

src/get.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
use serde::de::DeserializeOwned;
22
use serde_json::Value;
33

4-
use super::HttpResponseHead;
5-
use parse::{IsOk, ResponseBody, Unbuffered, MaybeOkResponse};
4+
use parsing::{IsOk, HttpResponseHead, ResponseBody, Unbuffered, MaybeOkResponse};
65
use error::*;
76

87
/// Response for a [get document request](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html).
@@ -12,6 +11,8 @@ pub struct GetResponseOf<T> {
1211
pub index: String,
1312
#[serde(rename = "_type")]
1413
pub ty: String,
14+
#[serde(rename = "_id")]
15+
pub id: String,
1516
#[serde(rename = "_version")]
1617
pub version: Option<u32>,
1718
pub found: bool,

src/index.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
use common::Shards;
2+
use parsing::{IsOk, HttpResponseHead, ResponseBody, Unbuffered, MaybeOkResponse};
3+
use error::*;
4+
5+
/// Response for an [index document request](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html).
6+
#[derive(Deserialize, Debug)]
7+
pub struct IndexResponse {
8+
#[serde(rename = "_index")]
9+
pub index: String,
10+
#[serde(rename = "_type")]
11+
pub ty: String,
12+
#[serde(rename = "_id")]
13+
pub id: String,
14+
#[serde(rename = "_version")]
15+
pub version: Option<u32>,
16+
pub created: bool,
17+
#[serde(rename = "_shards")]
18+
pub shards: Shards,
19+
}
20+
21+
impl IsOk for IndexResponse {
22+
fn is_ok<B: ResponseBody>(head: HttpResponseHead, body: Unbuffered<B>) -> Result<MaybeOkResponse<B>, ParseResponseError> {
23+
match head.status() {
24+
200...299 => Ok(MaybeOkResponse::ok(body)),
25+
_ => Ok(MaybeOkResponse::err(body)),
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)