All files / src utils.ts

100% Statements 15/15
100% Branches 7/7
100% Functions 4/4
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                                13x 3x       6x             3x     13x 13x 9x 3x 1x     2x   6x   11x       6x 1x     5x    
/*
 * Copyright © 2019 Lisk Foundation
 *
 * See the LICENSE file at the top-level directory of this distribution
 * for licensing information.
 *
 * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
 * no part of this software, including this file, may be copied, modified,
 * propagated, or distributed except according to the terms contained in the
 * LICENSE file.
 *
 * Removal or modification of this copyright notice is prohibited.
 *
 */
import { HashMap } from './api_types';
 
export const toQueryString = (obj: HashMap): string => {
	const parts = Object.keys(obj).reduce(
		(
			accumulator: ReadonlyArray<string>,
			key: string,
		): ReadonlyArray<string> => [
			...accumulator,
			`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`,
		],
		[],
	);
 
	return parts.join('&');
};
 
const urlParamRegex = /{[^}]+}/;
export const solveURLParams = (url: string, params: HashMap = {}): string => {
	if (Object.keys(params).length === 0) {
		if (url.match(urlParamRegex) !== null) {
			throw new Error('URL is not completely solved');
		}
 
		return url;
	}
	const solvedURL = Object.keys(params).reduce(
		(accumulator: string, key: string): string =>
			accumulator.replace(`{${key}}`, params[key]),
		url,
	);
 
	if (solvedURL.match(urlParamRegex) !== null) {
		throw new Error('URL is not completely solved');
	}
 
	return encodeURI(solvedURL);
};