Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Query parameter function #1298

Merged
merged 7 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions sdk/src/client/node_api/core/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use url::Url;
use crate::{
client::{
constants::{DEFAULT_API_TIMEOUT, DEFAULT_USER_AGENT},
node_api::query_tuples_to_query_string,
node_manager::node::{Node, NodeAuth},
Client, ClientInner, Result,
},
Expand Down Expand Up @@ -115,19 +116,28 @@ impl ClientInner {
pub async fn get_committee(&self, epoch_index: impl Into<Option<EpochIndex>> + Send) -> Result<CommitteeResponse> {
const PATH: &str = "api/core/v3/committee";

let epoch_index = epoch_index.into().map(|i| format!("epochIndex={i}"));
self.get_request(PATH, epoch_index.as_deref(), false, false).await
let query = query_tuples_to_query_string([epoch_index.into().map(|i| ("epochIndex", i.to_string()))]);

self.get_request(PATH, query.as_deref(), false, false).await
}

// Validators routes.

/// Returns information of all registered validators and if they are active.
/// GET JSON to /api/core/v3/validators
pub async fn get_validators(&self, page_size: Option<u32>) -> Result<ValidatorsResponse> {
pub async fn get_validators(
&self,
page_size: impl Into<Option<u32>> + Send,
cursor: impl Into<Option<String>> + Send,
) -> Result<ValidatorsResponse> {
const PATH: &str = "api/core/v3/validators";

let page_size = page_size.map(|i| format!("pageSize={i}"));
self.get_request(PATH, page_size.as_deref(), false, false).await
let query = query_tuples_to_query_string([
page_size.into().map(|i| ("pageSize", i.to_string())),
cursor.into().map(|i| ("cursor", i)),
]);

self.get_request(PATH, query.as_deref(), false, false).await
}

/// Return information about a validator.
Expand Down
67 changes: 29 additions & 38 deletions sdk/src/client/node_api/indexer/query_parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::fmt;
use serde::{Deserialize, Serialize};

use crate::{
client::{Error, Result},
client::{node_api::query_tuples_to_query_string, Error, Result},
types::block::{address::Bech32Address, slot::SlotIndex},
};

Expand Down Expand Up @@ -58,17 +58,7 @@ impl QueryParameters {

/// Converts parameters to a single String.
pub fn to_query_string(&self) -> Option<String> {
if self.0.is_empty() {
None
} else {
Some(
self.0
.iter()
.map(QueryParameter::to_query_string)
.collect::<Vec<String>>()
.join("&"),
)
}
query_tuples_to_query_string(self.0.iter().map(|q| Some(q.to_query_tuple())))
}
}

Expand Down Expand Up @@ -131,32 +121,32 @@ pub enum QueryParameter {
}

impl QueryParameter {
fn to_query_string(&self) -> String {
fn to_query_tuple(&self) -> (&'static str, String) {
match self {
Self::Address(v) => format!("address={v}"),
Self::AccountAddress(v) => format!("accountAddress={v}"),
Self::CreatedAfter(v) => format!("createdAfter={v}"),
Self::CreatedBefore(v) => format!("createdBefore={v}"),
Self::Cursor(v) => format!("cursor={v}"),
Self::ExpirationReturnAddress(v) => format!("expirationReturnAddress={v}"),
Self::ExpiresAfter(v) => format!("expiresAfter={v}"),
Self::ExpiresBefore(v) => format!("expiresBefore={v}"),
Self::Governor(v) => format!("governor={v}"),
Self::HasExpiration(v) => format!("hasExpiration={v}"),
Self::HasNativeTokens(v) => format!("hasNativeTokens={v}"),
Self::HasStorageDepositReturn(v) => format!("hasStorageDepositReturn={v}"),
Self::HasTimelock(v) => format!("hasTimelock={v}"),
Self::Issuer(v) => format!("issuer={v}"),
Self::MaxNativeTokenCount(v) => format!("maxNativeTokenCount={v}"),
Self::MinNativeTokenCount(v) => format!("minNativeTokenCount={v}"),
Self::PageSize(v) => format!("pageSize={v}"),
Self::Sender(v) => format!("sender={v}"),
Self::StateController(v) => format!("stateController={v}"),
Self::StorageDepositReturnAddress(v) => format!("storageDepositReturnAddress={v}"),
Self::Tag(v) => format!("tag={v}"),
Self::TimelockedAfter(v) => format!("timelockedAfter={v}"),
Self::TimelockedBefore(v) => format!("timelockedBefore={v}"),
Self::UnlockableByAddress(v) => format!("unlockableByAddress={v}"),
Self::Address(v) => ("address", v.to_string()),
Self::AccountAddress(v) => ("accountAddress", v.to_string()),
Self::CreatedAfter(v) => ("createdAfter", v.to_string()),
Self::CreatedBefore(v) => ("createdBefore", v.to_string()),
Self::Cursor(v) => ("cursor", v.to_string()),
Self::ExpirationReturnAddress(v) => ("expirationReturnAddress", v.to_string()),
Self::ExpiresAfter(v) => ("expiresAfter", v.to_string()),
Self::ExpiresBefore(v) => ("expiresBefore", v.to_string()),
Self::Governor(v) => ("governor", v.to_string()),
Self::HasExpiration(v) => ("hasExpiration", v.to_string()),
Self::HasNativeTokens(v) => ("hasNativeTokens", v.to_string()),
Self::HasStorageDepositReturn(v) => ("hasStorageDepositReturn", v.to_string()),
Self::HasTimelock(v) => ("hasTimelock", v.to_string()),
Self::Issuer(v) => ("issuer", v.to_string()),
Self::MaxNativeTokenCount(v) => ("maxNativeTokenCount", v.to_string()),
Self::MinNativeTokenCount(v) => ("minNativeTokenCount", v.to_string()),
Self::PageSize(v) => ("pageSize", v.to_string()),
Self::Sender(v) => ("sender", v.to_string()),
Self::StateController(v) => ("stateController", v.to_string()),
Self::StorageDepositReturnAddress(v) => ("storageDepositReturnAddress", v.to_string()),
Self::Tag(v) => ("tag", v.to_string()),
Self::TimelockedAfter(v) => ("timelockedAfter", v.to_string()),
Self::TimelockedBefore(v) => ("timelockedBefore", v.to_string()),
Self::UnlockableByAddress(v) => ("unlockableByAddress", v.to_string()),
}
}

Expand Down Expand Up @@ -192,7 +182,8 @@ impl QueryParameter {

impl fmt::Display for QueryParameter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_query_string())
let query_tuple = self.to_query_tuple();
write!(f, "{}={}", query_tuple.0, query_tuple.1)
}
}

Expand Down
11 changes: 11 additions & 0 deletions sdk/src/client/node_api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,14 @@ pub mod mqtt;
#[cfg_attr(docsrs, doc(cfg(feature = "participation")))]
pub mod participation;
pub mod plugin;

pub(crate) fn query_tuples_to_query_string(
query: impl IntoIterator<Item = Option<(&'static str, String)>>,
kwek20 marked this conversation as resolved.
Show resolved Hide resolved
) -> Option<String> {
let query = query
.into_iter()
.filter_map(|q| q.map(|q| format!("{}={}", q.0, q.1)))
.collect::<Vec<_>>();

if query.is_empty() { None } else { Some(query.join("&")) }
}