jsonrpc/
jsonrpc_message.rs

1// Copyright 2016 Bruno Medeiros
2//
3// Licensed under the Apache License, Version 2.0 
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>. 
5// This file may not be copied, modified, or distributed
6// except according to those terms.
7
8
9extern crate serde_json;
10extern crate serde;
11
12use serde_json::Value;
13
14use jsonrpc_request::*;
15use jsonrpc_response::*;
16use json_util::*;
17
18/* -----------------  Message  ----------------- */
19
20#[derive(Debug, PartialEq, Clone)]
21pub enum Message {
22    Request(Request),
23    Response(Response),
24}
25
26impl From<Response> for Message {
27    fn from(response: Response) -> Self {
28        Message::Response(response)
29    }
30}
31
32impl From<Request> for Message {
33    fn from(request: Request) -> Self {
34        Message::Request(request)
35    }
36}
37
38impl serde::Serialize for Message {
39    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
40        where S: serde::Serializer
41    {
42        match *self {
43            Message::Request(ref request) => request.serialize(serializer),
44            Message::Response(ref response) => response.serialize(serializer),
45        }
46    }
47}
48
49impl serde::Deserialize for Message {
50    fn deserialize<DE>(deserializer: &mut DE) -> Result<Self, DE::Error>
51        where DE: serde::Deserializer 
52    {
53        let mut helper = SerdeJsonDeserializerHelper(deserializer);
54        let value = try!(Value::deserialize(helper.0));
55        let json_obj = try!(helper.as_Object(value));
56        
57        if json_obj.contains_key("method") {
58            let request = serde_json::from_value::<Request>(Value::Object(json_obj));
59            Ok(Message::Request(try!(request.map_err(to_de_error))))
60        } else {
61            let response = serde_json::from_value::<Response>(Value::Object(json_obj));
62            Ok(Message::Response(try!(response.map_err(to_de_error))))
63        }
64    }
65}
66
67
68#[cfg(test)]
69pub mod message_tests {
70    
71    use super::*;
72    use jsonrpc_common::*;
73    
74    use json_util::*;
75    use json_util::test_util::*;
76    
77    use jsonrpc_response::*;
78    use jsonrpc_response::response_tests::sample_json_obj;
79    use jsonrpc_request::*;
80    
81    #[test]
82    fn test_Message() {
83        
84        // Attempt Method parse
85        test_error_de::<Message>(r#"{ "jsonrpc": "2.0", "method":"foo" }"#, "Property `params` is missing");
86        
87        // Attempt Response parse
88        test_error_de::<Message>(r#"{ "jsonrpc": "2.0"}"#, "Property `id` is missing");
89        
90        test_serde::<Message>(&Response::new_result(Id::Null, sample_json_obj(100)).into());
91        
92        let sample_params = unwrap_object(sample_json_obj(123));
93        test_serde::<Message>(&Request::new(1, "myMethod".to_string(), sample_params).into());
94    }
95    
96}