use super::ApiPaths;
use anyhow::Context as _;
use enumflags2::BitFlags;
use jsonrpsee::core::traits::ToRpcParams;
use serde::{Deserialize, Serialize};
use std::{marker::PhantomData, time::Duration};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request<T = serde_json::Value> {
pub method_name: std::borrow::Cow<'static, str>,
pub params: serde_json::Value,
#[serde(skip)]
pub result_type: PhantomData<T>,
#[serde(skip)]
pub api_path: ApiPaths,
#[serde(skip)]
pub timeout: Duration,
}
impl<T> Request<T> {
pub fn set_timeout(&mut self, timeout: Duration) {
self.timeout = timeout;
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.set_timeout(timeout);
self
}
pub fn set_api_path(&mut self, api_path: ApiPaths) {
self.api_path = api_path;
}
pub fn with_api_path(mut self, api_path: ApiPaths) -> Self {
self.set_api_path(api_path);
self
}
pub fn map_ty<U>(self) -> Request<U> {
Request {
method_name: self.method_name,
params: self.params,
result_type: PhantomData,
api_path: self.api_path,
timeout: self.timeout,
}
}
pub fn max_api_path(api_paths: BitFlags<ApiPaths>) -> anyhow::Result<ApiPaths> {
api_paths.iter().max().context("No supported versions")
}
}
impl<T> ToRpcParams for Request<T> {
fn to_rpc_params(self) -> Result<Option<Box<serde_json::value::RawValue>>, serde_json::Error> {
Ok(Some(serde_json::value::to_raw_value(&self.params)?))
}
}