breez_sdk_core/lsps0/
jsonrpc.rs

1extern crate serde;
2extern crate serde_json;
3
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7#[derive(Debug, Serialize, Deserialize)]
8pub struct RpcServerMessage {
9    pub jsonrpc: String,
10
11    #[serde(flatten)]
12    pub body: RpcServerMessageBody,
13}
14
15#[derive(Debug, Serialize, Deserialize)]
16#[serde(untagged)]
17pub enum RpcServerMessageBody {
18    Notification { method: String, params: Value },
19    Response { id: String, result: Value },
20    Error { id: String, error: RpcError },
21}
22
23#[derive(Debug, Serialize, Deserialize)]
24pub struct RpcRequest<TParams> {
25    pub id: String,
26    pub jsonrpc: String,
27    pub method: String,
28    pub params: TParams,
29}
30
31#[derive(Debug, Serialize, Deserialize)]
32pub struct RpcError {
33    pub code: i64,
34    pub message: String,
35    pub data: Option<Value>,
36}
37
38#[cfg(test)]
39mod tests {
40    use crate::lsps0::jsonrpc::{RpcServerMessage, RpcServerMessageBody};
41
42    #[test]
43    fn test_deserialize_notification() {
44        let json = r#"{"jsonrpc":"2.0","method":"test","params":{}}"#;
45        let notification = serde_json::from_str::<RpcServerMessage>(json).unwrap();
46        assert!(matches!(
47            notification.body,
48            RpcServerMessageBody::Notification { .. }
49        ))
50    }
51
52    #[test]
53    fn test_deserialize_response() {
54        let json = r#"{"jsonrpc":"2.0","id":"test","result":{}}"#;
55        let notification = serde_json::from_str::<RpcServerMessage>(json).unwrap();
56        assert!(matches!(
57            notification.body,
58            RpcServerMessageBody::Response { .. }
59        ))
60    }
61
62    #[test]
63    fn test_deserialize_error() {
64        let json = r#"{"jsonrpc":"2.0","id":"test","error":{"code":1,"message":"test","data":{}}}"#;
65        let error = serde_json::from_str::<RpcServerMessage>(json).unwrap();
66        assert!(matches!(error.body, RpcServerMessageBody::Error { .. }))
67    }
68
69    #[test]
70    fn test_deserialize_error_without_data() {
71        let json = r#"{"jsonrpc":"2.0","id":"test","error":{"code":1,"message":"test"}}"#;
72        let error = serde_json::from_str::<RpcServerMessage>(json).unwrap();
73        assert!(matches!(error.body, RpcServerMessageBody::Error { .. }))
74    }
75}