use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Deserialize)]
pub struct JsonRpcRequest {
#[serde(rename = "jsonrpc")]
pub _jsonrpc: String,
pub id: Option<Value>,
pub method: String,
pub params: Option<Value>,
}
#[derive(Debug, Serialize)]
pub struct JsonRpcResponse {
pub jsonrpc: String,
pub id: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<JsonRpcError>,
}
impl JsonRpcResponse {
pub fn success(id: Option<Value>, result: Value) -> Self {
Self { jsonrpc: "2.0".to_string(), id, result: Some(result), error: None }
}
pub fn error(id: Option<Value>, error: JsonRpcError) -> Self {
Self { jsonrpc: "2.0".to_string(), id, result: None, error: Some(error) }
}
pub fn null(id: Option<Value>) -> Self {
Self { jsonrpc: "2.0".to_string(), id, result: Some(Value::Null), error: None }
}
}
#[derive(Debug, Serialize, Clone)]
pub struct JsonRpcError {
pub code: i32,
pub message: String,
pub data: Option<Value>,
}
impl JsonRpcError {
pub fn new(code: i32, message: impl Into<String>) -> Self {
Self { code, message: message.into(), data: None }
}
pub fn with_data(code: i32, message: impl Into<String>, data: Value) -> Self {
Self { code, message: message.into(), data: Some(data) }
}
}
impl std::fmt::Display for JsonRpcError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.code, self.message)
}
}
impl std::error::Error for JsonRpcError {}