Skip to content

Commit

Permalink
Merge pull request #90 from alchemyplatform/dp/multivalued-params
Browse files Browse the repository at this point in the history
Append [] to array query params
  • Loading branch information
dphilipson authored Feb 6, 2022
2 parents 690b263 + 0e6be49 commit a3d3c85
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,8 +266,9 @@ function callAlchemyRestEndpoint<T>({
callback = noop,
processResponse = identity,
}: CallAlchemyRestEndpoint<T>): Promise<T> {
const fixedParams = fixArrayQueryParams(params);
const promise = (async () => {
const result = await restSender.sendRestPayload(path, params);
const result = await restSender.sendRestPayload(path, fixedParams);
return processResponse(result);
})();
callWhenDone(promise, callback);
Expand Down Expand Up @@ -383,3 +384,26 @@ function noop(): void {
function identity<T>(x: T): T {
return x;
}

/**
* Alchemy's APIs receive multivalued params via keys with `[]` at the end.
* Update any query params whose values are arrays to match this convention.
*/
function fixArrayQueryParams(params: Record<string, any>): Record<string, any> {
const result: Record<string, any> = {};
Object.keys(params).forEach((key) => {
const value = params[key];
const fixedKey = Array.isArray(value) ? toArrayKey(key) : key;
result[fixedKey] = value;
});
return result;
}

function toArrayKey(key: string): string {
return endsWith(key, "[]") ? key : `${key}[]`;
}

function endsWith(s: string, ending: string): boolean {
const index = s.lastIndexOf(ending);
return index >= 0 && index === s.length - ending.length;
}

0 comments on commit a3d3c85

Please sign in to comment.