use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Serialize)]
pub struct RpcRequest {
pub id: u64,
pub method: String,
pub params: Value,
}
impl RpcRequest {
pub fn new(id: u64, method: impl Into<String>, params: Value) -> Self {
Self {
id,
method: method.into(),
params,
}
}
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string(self)
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct RpcResponse {
pub id: u64,
#[serde(default)]
pub result: Value,
#[serde(default)]
pub error: Option<RpcError>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct RpcError {
pub code: i64,
pub message: String,
}
impl RpcResponse {
pub fn is_success(&self) -> bool {
self.error.is_none()
}
pub fn into_result(self) -> Result<Value, (i64, String)> {
match self.error {
Some(e) => Err((e.code, e.message)),
None => Ok(self.result),
}
}
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SurrealQueryResult {
#[serde(default)]
pub time: String,
#[serde(default)]
pub status: String,
#[serde(default)]
pub result: Value,
}
impl SurrealQueryResult {
pub fn is_ok(&self) -> bool {
self.status == "OK"
}
pub fn take<T: for<'de> Deserialize<'de>>(&self) -> Result<Vec<T>, serde_json::Error> {
if self.result.is_null() {
return Ok(Vec::new());
}
serde_json::from_value(self.result.clone())
}
pub fn take_first<T: for<'de> Deserialize<'de>>(&self) -> Result<Option<T>, serde_json::Error> {
let items: Vec<T> = self.take()?;
Ok(items.into_iter().next())
}
}
pub fn signin_params(user: &str, pass: &str) -> Value {
serde_json::json!([{
"user": user,
"pass": pass,
}])
}
pub fn use_params(ns: &str, db: &str) -> Value {
serde_json::json!([ns, db])
}
pub fn query_params(sql: &str, bindings: Option<&Value>) -> Value {
match bindings {
Some(b) if !b.as_object().map(|o| o.is_empty()).unwrap_or(true) => {
serde_json::json!([sql, b])
}
_ => serde_json::json!([sql]),
}
}
pub fn set_params(key: &str, value: &Value) -> Value {
serde_json::json!([key, value])
}