Commit d9ea46f6 authored by tom's avatar tom

[skip ci] support array-like query params in API resource calls

parent 0a8a82e6
import buildUrl from './buildUrl';
test('builds URL for resource without path params', () => {
const url = buildUrl('config_backend_version');
expect(url).toBe('https://localhost:3003/api/v2/config/backend-version');
});
test('builds URL for resource with path params', () => {
const url = buildUrl('block', { height_or_hash: '42' });
expect(url).toBe('https://localhost:3003/api/v2/blocks/42');
});
describe('falsy query parameters', () => {
test('leaves "false" as query parameter', () => {
const url = buildUrl('block', { height_or_hash: '42' }, { includeTx: false });
expect(url).toBe('https://localhost:3003/api/v2/blocks/42?includeTx=false');
});
test('leaves "null" as query parameter', () => {
const url = buildUrl('block', { height_or_hash: '42' }, { includeTx: null });
expect(url).toBe('https://localhost:3003/api/v2/blocks/42?includeTx=null');
});
test('strips out empty string as query parameter', () => {
const url = buildUrl('block', { height_or_hash: '42' }, { includeTx: null, sort: '' });
expect(url).toBe('https://localhost:3003/api/v2/blocks/42?includeTx=null');
});
test('strips out "undefined" as query parameter', () => {
const url = buildUrl('block', { height_or_hash: '42' }, { includeTx: null, sort: undefined });
expect(url).toBe('https://localhost:3003/api/v2/blocks/42?includeTx=null');
});
});
test('builds URL with array-like query parameters', () => {
const url = buildUrl('block', { height_or_hash: '42' }, { includeTx: [ '0x11', '0x22' ], sort: 'asc' });
expect(url).toBe('https://localhost:3003/api/v2/blocks/42?includeTx%5B0%5D=0x11&includeTx%5B1%5D=0x22&sort=asc');
});
test('builds URL for resource with custom API endpoint', () => {
const url = buildUrl('token_verified_info', { chainId: '42', hash: '0x11' });
expect(url).toBe('https://localhost:3005/api/v1/chains/42/token-infos/0x11');
});
......@@ -19,7 +19,13 @@ export default function buildUrl<R extends ResourceName>(
queryParams && Object.entries(queryParams).forEach(([ key, value ]) => {
// there are some pagination params that can be null or false for the next page
value !== undefined && value !== '' && url.searchParams.append(key, String(value));
if (value !== undefined && value !== '') {
if (Array.isArray(value)) {
value.forEach((v, i) => url.searchParams.append(`${ key }[${ i }]`, String(v)));
} else {
url.searchParams.append(key, String(value));
}
}
});
return url.toString();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment