jsonrpce 0.1.0

JSON-RPC 2.0 for Rust
Documentation
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::Error;

/// JSON-RPC 2.0 Version Constant
const VERSION: &str = "2.0";

/// A representation of the incoming JSON-RPC request.
#[derive(Debug, Deserialize)]
pub struct Request {
    /// Must be "2.0"
    pub jsonrpc: String,

    /// The name of the method to be invoked.
    pub method: String,

    /// A Structured value that holds the parameter values.
    #[serde(default)]
    pub params: Value,

    /// An identifier established by the Client.
    /// If missing, it is a Notification.
    pub id: Option<Value>,
}

/// A representation of the outgoing JSON-RPC response.
#[derive(Debug, Serialize)]
pub struct Response {
    pub jsonrpc: &'static str,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<Error>,

    pub id: Option<Value>,
}

impl Response {
    /// Create a success response
    pub fn success(id: Option<Value>, result: Value) -> Self {
        Self {
            jsonrpc: VERSION,
            result: Some(result),
            error: None,
            id: id.or(Some(Value::Null)),
        }
    }

    /// Create an error response
    pub fn error(id: Option<Value>, error: Error) -> Self {
        Self {
            jsonrpc: VERSION,
            result: None,
            error: Some(error),
            id: id.or(Some(Value::Null)),
        }
    }
}