Skip to content

Commit

Permalink
refactor to improve readability (AcalaNetwork#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
xlc authored and kostekIV committed May 9, 2024
1 parent 8bd23a8 commit 972527f
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/middlewares/methods/inject_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ impl Middleware<CallRequest, CallResult> for InjectParamsMiddleware {
if param.ty == "BlockNumber" {
if let Some(number) = request.params.get(idx).and_then(|x| x.as_u64()) {
let (_, finalized) = self.finalized.read().await;
// avoid cache unfinalized data
if number > finalized {
context.insert(BypassCache(true));
}
Expand All @@ -119,37 +120,43 @@ impl Middleware<CallRequest, CallResult> for InjectParamsMiddleware {
};

let idx = self.get_index();
match request.params.len() {
len if len > idx + 1 => {
// unexpected number of params
let min_len = idx + 1;
let len = request.params.len();

match len.cmp(&min_len) {
std::cmp::Ordering::Greater => {
// too many params, no injection needed
return handle_request(request).await;
}
len if len <= idx => {
// without current block
let params_passed = request.params.len();
while request.params.len() < idx {
let current = request.params.len();
if self.params[current].optional {
std::cmp::Ordering::Less => {
// too few params

// ensure missing params are optional and push null
for i in len..(min_len - 1) {
if self.params[i].optional {
request.params.push(JsonValue::Null);
} else {
let (required, optional) = self.params_count();
return Err(errors::invalid_params(format!(
"Expected {:?} parameters ({:?} optional), {:?} found instead",
required + optional,
optional,
params_passed
len
)));
}
}

// Set param to null, it will be replaced later
request.params.push(JsonValue::Null);
}
_ => {} // full params, block potentially might be null
std::cmp::Ordering::Equal => {
// same number of params, no need to push params
}
};

// Here we are sure we have full params in the request, but it still might be set to null
async move {
if request.params[idx] == JsonValue::Null {
if request.params[idx].is_null() {
let to_inject = self.get_parameter().await;
tracing::trace!("Injected param {} to method {}", &to_inject, request.method);
request.params[idx] = to_inject;
Expand Down

0 comments on commit 972527f

Please sign in to comment.