Function jrpc::parse_request [] [src]

pub fn parse_request<M>(json: &str) -> Result<Request<M, Value>, Error<Value>> where
    M: Serialize + DeserializeOwned

Parse a json string, returning either:

  • The parsed Request
  • An Error object created according to the jsonrpc spec (with a useful reason/message).

This parses the json in stages and will correctly return one of the following errors on failure:

  • ParseError
  • InvalidRequest
  • MethodNotFound

Reminder: It is up to the user to return the InvalidParams error if the request.params is invalid.

Examples

Well formed Request

extern crate serde_json;
use jrpc::{Id, Request, V2_0};

let params: Vec<u32> = vec![1, 2, 3];
let request = Request::with_params(
    Id::from(4),
    "CreateFoo".to_string(),
    Some(params.clone()),
);
let json = r#"
{
    "jsonrpc": "2.0",
    "method": "CreateFoo",
    "params": [1,2,3],
    "id": 4
}
"#;

let result: Request<String, _> = jrpc::parse_request(json).unwrap();
let result_params: Vec<u32> = serde_json::from_value(
    result.params.unwrap()).unwrap();
assert_eq!(params, result_params);
assert_eq!(request.method, result.method);
assert_eq!(request.id, result.id);

Error: ParseError

extern crate serde_json;
use jrpc::{Id, Request, V2_0};

let params: Vec<u32> = vec![1, 2, 3];
let json = r#"
Not Valid JSON...
"#;

let result: Result<jrpc::Request<String, jrpc::Value>, jrpc::Error<jrpc::Value>> =
    jrpc::parse_request(json);

let error = result.unwrap_err();
assert_eq!(error.error.code, jrpc::ErrorCode::ParseError);

Error: InvalidRequest

extern crate serde_json;
use jrpc::{Id, Request, V2_0};

let params: Vec<u32> = vec![1, 2, 3];
let json = r#"
{
    "type": "valid json",
    "but": "not jsonrpc!"
}
"#;

let result: Result<jrpc::Request<String, jrpc::Value>, jrpc::Error<jrpc::Value>> =
    jrpc::parse_request(json);

let error = result.unwrap_err();
assert_eq!(error.error.code, jrpc::ErrorCode::InvalidRequest);
assert!(error.error.message.contains("missing field `jsonrpc`"));
assert_eq!(error.id, jrpc::Id::Null);

Error: MethodNotFound

#[macro_use] extern crate serde_derive;
extern crate serde_json;
use jrpc::{Id, Request, V2_0};

#[derive(Debug, Serialize, Deserialize)]
enum Method {
    One,
    Two,
}

let params: Vec<u32> = vec![1, 2, 3];
let json = r#"
{
    "jsonrpc": "2.0",
    "method": "Three",
    "params": [1,2,3],
    "id": 4
}
"#;

let result: Result<jrpc::Request<Method, jrpc::Value>, jrpc::Error<jrpc::Value>> =
    jrpc::parse_request(json);

let error = result.unwrap_err();
assert_eq!(error.error.code, jrpc::ErrorCode::MethodNotFound);
assert!(error.error.message.contains(
    "unknown variant `Three`, expected `One` or `Two`"));
assert_eq!(error.id, jrpc::Id::Int(4));