use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::error::Error;
use crate::request::Id;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Response {
#[serde(skip_serializing_if = "Option::is_none")]
pub jsonrpc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<Error>,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<Id>,
}
impl Response {
pub fn success(result: Value, id: Option<Id>) -> Self {
Response::success_v2(result, id)
}
pub fn error(error: Error, id: Option<Id>) -> Self {
Response::error_v2(error, id)
}
pub fn success_v2(result: Value, id: Option<Id>) -> Self {
Response {
jsonrpc: Some("2.0".to_string()),
version: None,
result: Some(result),
error: None,
id,
}
}
pub fn error_v2(error: Error, id: Option<Id>) -> Self {
Response {
jsonrpc: Some("2.0".to_string()),
version: None,
result: None,
error: Some(error),
id,
}
}
pub fn success_v1_1(result: Value, id: Option<Id>) -> Self {
Response {
jsonrpc: None,
version: Some("1.1".to_string()),
result: Some(result),
error: None,
id,
}
}
pub fn error_v1_1(error: Error, id: Option<Id>) -> Self {
Response {
jsonrpc: None,
version: Some("1.1".to_string()),
result: None,
error: Some(error),
id,
}
}
pub fn success_v1(result: Value, id: Option<Id>) -> Self {
Response {
jsonrpc: None,
version: None,
result: Some(result),
error: None,
id,
}
}
pub fn error_v1(error: Error, id: Option<Id>) -> Self {
Response {
jsonrpc: None,
version: None,
result: None,
error: Some(error),
id,
}
}
pub fn is_success(&self) -> bool {
self.error.is_none()
}
pub fn is_error(&self) -> bool {
self.error.is_some()
}
}