added batch request builder

This commit is contained in:
Mahesh Bansod 2021-09-30 23:13:44 +05:30
parent bb1786b359
commit 003735587e
2 changed files with 54 additions and 0 deletions

View File

@ -1,5 +1,52 @@
use serde::{Deserialize, Serialize};
use crate::utils::generate_id;
type RawBatchRequest = Vec<RawRequest>;
pub type BatchResponse = Vec<serde_json::Value>;
/// Used to build a batch request. This object is created using the `batch_request` function of the crate
pub struct BatchRequestBuilder {
requests: RawBatchRequest,
}
impl BatchRequestBuilder {
pub fn new() -> BatchRequestBuilder {
BatchRequestBuilder { requests: vec![] }
}
/// Add a request to the batch request
pub fn add_request(
&mut self,
method: &str,
params: serde_json::Value,
) -> &mut BatchRequestBuilder {
self.requests.push(RawRequest::new(
Some(generate_id()),
method.to_string(),
Some(params),
));
self
}
// Add a new notification to the batch request
pub fn add_notification(
&mut self,
method: &str,
params: serde_json::Value,
) -> &mut BatchRequestBuilder {
self.requests
.push(RawRequest::new(None, method.to_string(), Some(params)));
self
}
/// Send the batch request
/// TODO: mmm.. maybe find a way to add the RawResponse object here somehow???
pub fn send() -> Result<BatchResponse, Vec<RpcError>> {
unimplemented!()
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RawRequest {
pub jsonrpc: String,

View File

@ -1,6 +1,7 @@
mod entities;
mod utils;
use entities::BatchRequestBuilder;
use entities::RawRequest;
use entities::RawResponse;
pub use entities::RpcError;
@ -21,6 +22,12 @@ pub fn new(host: &str) -> Client {
}
}
/// Creates a new BatchRequestBuilder object which can be used to build a batch request which
/// may contain both requests and notifications(i.e. requests without an id)
pub fn batch_request() -> BatchRequestBuilder {
BatchRequestBuilder::new()
}
impl Client {
///Send a request
pub async fn send_request<T: serde::de::DeserializeOwned + std::fmt::Debug>(