All files / src/http/utility parse-querystring.ts

94.74% Statements 36/38
92.86% Branches 13/14
100% Functions 4/4
94.74% Lines 36/38

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 7819x         4x   4x               4x   4x         4x 4x   4x 4x 4x 4x   4x 34x   34x   34x 8x 26x 8x 2x 2x   2x     8x 5x 2x   3x       8x 8x   18x       4x       2x 2x   2x 4x   4x     2x     19x  
import Querystring from 'querystring';
 
import JsonObject from 'http/type/json-object';
 
function isNumericKey(key: string): boolean {
	const parsed_key = parseInt(key, 10);
 
	return isNaN(parsed_key) === false;
}
 
function mergeValue(
	result: Record<string, unknown>,
	key: string,
	value: any
): void {
	const brace_index = key.indexOf('[');
 
	Iif (brace_index === -1) {
		result[key] = value;
		return;
	}
 
	const prefix = key.slice(0, brace_index);
	const suffix = key.slice(brace_index);
 
	let index = 0;
	let previous_key = prefix;
	let current_key = '';
	let target = result;
 
	while (index < suffix.length) {
		const character = suffix[index];
 
		index++;
 
		if (character === '[') {
			current_key = '';
		} else if (character === ']') {
			if (previous_key === '') {
				const array = (target as unknown) as any[];
				const index_key = Math.max(0, array.length - 1);
 
				previous_key = index_key.toString();
			}
 
			if (target[previous_key] === undefined) {
				if (current_key === '' || isNumericKey(current_key)) {
					target[previous_key] = [];
				} else {
					target[previous_key] = {};
				}
			}
 
			target = target[previous_key] as Record<string, unknown>;
			previous_key = current_key;
		} else {
			current_key += character;
		}
	}
 
	target[current_key] = value;
}
 
function parseQuerystring(querystring: string): JsonObject {
	const result = {};
	const raw_data = Querystring.parse(querystring);
 
	Object.keys(raw_data).forEach((key) => {
		const value = raw_data[key];
 
		mergeValue(result, key, value);
	});
 
	return result;
}
 
export default parseQuerystring;