jsonrpc_client_core/
response.rs

1// Copyright 2017 Amagicom AB.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use jsonrpc_core::types::{Id, Output, Version};
10use serde;
11use serde_json;
12use {ErrorKind, Result, ResultExt};
13
14/// Parses a binary response into json, extracts the "result" field and tries to deserialize that
15/// to the desired type.
16pub fn parse<R>(response_raw: &[u8], expected_id: &Id) -> Result<R>
17where
18    R: serde::de::DeserializeOwned,
19{
20    let response: Output = serde_json::from_slice(response_raw)
21        .chain_err(|| ErrorKind::ResponseError("Not valid json"))?;
22    ensure!(
23        response.version() == Some(Version::V2),
24        ErrorKind::ResponseError("Not JSON-RPC 2.0 compatible")
25    );
26    ensure!(
27        response.id() == expected_id,
28        ErrorKind::ResponseError("Response id not equal to request id")
29    );
30    match response {
31        Output::Success(success) => {
32            trace!("Received json result: {}", success.result);
33            serde_json::from_value(success.result)
34                .chain_err(|| ErrorKind::ResponseError("Not valid for target type"))
35        }
36        Output::Failure(failure) => bail!(ErrorKind::JsonRpcError(failure.error)),
37    }
38}