1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*!
Utility types for response parsing.
# Examples
Implement `IsOk` for a deserialisable type that converts a http response into a concrete type.
This example defines a search response that, for whatever reason, only includes the `took` field:
```
# extern crate serde;
# #[macro_use] extern crate serde_derive;
# extern crate elastic;
# use std::io::Read;
# use elastic::prelude::*;
# use elastic::error::ParseResponseError;
# use elastic::client::responses::parse::*;
#[derive(Deserialize)]
struct MyResponse {
took: u64
}
impl IsOk for MyResponse {
fn is_ok<B>(head: HttpResponseHead, body: Unbuffered<B>) -> Result<MaybeOkResponse<B>, ParseResponseError>
where B: ResponseBody
{
match head.status() {
// If the status is 2xx then return the response with `ok: true`
// The body will be parsed as a `MyResponse`.
200...299 => Ok(MaybeOkResponse::ok(body)),
// Otherwise return the response with `ok: false`
// The body will be parsed as an `ApiError`.
_ => Ok(MaybeOkResponse::err(body))
}
}
}
# fn main() {}
```
The `MyResponse` type can then be used for deserialising a concrete response:
```no_run
# extern crate serde;
# #[macro_use] extern crate serde_derive;
# extern crate elastic;
# use elastic::prelude::*;
# use elastic::error::{ErrorKind, ParseResponseError};
# use elastic::client::responses::parse::*;
# #[derive(Deserialize)]
# struct MyResponse {
# took: u64
# }
# impl IsOk for MyResponse {
# fn is_ok<B>(head: HttpResponseHead, body: Unbuffered<B>) -> Result<MaybeOkResponse<B>, ParseResponseError>
# where B: ResponseBody
# {
# match head.status() {
# 200...299 => Ok(MaybeOkResponse::ok(body)),
# _ => Ok(MaybeOkResponse::err(body))
# }
# }
# }
# fn main() {
# let client = Client::new(RequestParams::default()).unwrap();
# let req = SearchRequest::new("");
let response = client.request(req)
.send()
.and_then(into_response::<MyResponse>);
match response {
Ok(response) => {
println!("took: {}", response.took);
},
Err(e) => {
match *e.kind() {
ErrorKind::Api(ref e) => {
// handle a REST API error
},
ref e => {
// handle a HTTP or JSON error
}
}
}
}
# }
```
You can also parse the response body into a temporary `serde_json::Value` if the status code isn't enough to determine if it's ok.
This will consume the `UnbufferedResponse` and return a `BufferedResponse` instead that keeps the response body private for later handlers to use.
See the [`IsOk`][IsOk] trait for more details.
[IsOk]: trait.IsOk.html
*/
pub use ;