use serde::{Deserialize, Serialize};
use serde_json::Value;
#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct RpcRequest {
pub jsonrpc: String,
#[serde(default)]
pub id: Value,
pub method: String,
#[serde(default)]
pub params: Value,
}
#[allow(dead_code)]
impl RpcRequest {
pub fn is_notification(&self) -> bool {
self.id.is_null()
}
}
#[derive(Debug, Serialize)]
pub struct RpcResponse {
pub jsonrpc: &'static str,
pub id: Value,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<RpcError>,
}
impl RpcResponse {
pub fn success(id: Value, result: Value) -> Self {
Self {
jsonrpc: "2.0",
id,
result: Some(result),
error: None,
}
}
pub fn error(id: Value, code: i32, message: impl Into<String>, data: Option<Value>) -> Self {
Self {
jsonrpc: "2.0",
id,
result: None,
error: Some(RpcError {
code,
message: message.into(),
data,
}),
}
}
pub fn parse_error() -> Self {
Self::error(Value::Null, -32700, "Parse error", None)
}
#[allow(dead_code)]
pub fn invalid_request(id: Value) -> Self {
Self::error(id, -32600, "Invalid request", None)
}
pub fn method_not_found(id: Value, method: &str) -> Self {
Self::error(id, -32601, format!("Method not found: {}", method), None)
}
pub fn invalid_params(id: Value, message: impl Into<String>) -> Self {
Self::error(id, -32602, message, None)
}
#[allow(dead_code)]
pub fn internal_error(id: Value, message: impl Into<String>) -> Self {
Self::error(id, -32603, message, None)
}
pub fn toondb_error(id: Value, message: impl Into<String>) -> Self {
Self::error(id, -32001, message, None)
}
}
#[derive(Debug, Serialize)]
pub struct RpcError {
pub code: i32,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}