Commit 8aa64264 authored by Michael Lunøe's avatar Michael Lunøe Committed by Olena Horal-Koretska

Feat(queryToObject): add option to handle arrays

Add option to not overwrite values, but instead
gather them into an array, so we can handle
queries with array values
parent 06a3f976
......@@ -334,17 +334,32 @@ export function getWebSocketUrl(path) {
* Convert search query into an object
*
* @param {String} query from "document.location.search"
* @param {Object} options
* @param {Boolean} options.gatherArrays - gather array values into an Array
* @returns {Object}
*
* ex: "?one=1&two=2" into {one: 1, two: 2}
*/
export function queryToObject(query) {
export function queryToObject(query, options = {}) {
const { gatherArrays = false } = options;
const removeQuestionMarkFromQuery = String(query).startsWith('?') ? query.slice(1) : query;
return removeQuestionMarkFromQuery.split('&').reduce((accumulator, curr) => {
const [key, value] = curr.split('=');
if (value !== undefined) {
accumulator[decodeURIComponent(key)] = decodeURIComponent(value);
if (value === undefined) {
return accumulator;
}
const decodedValue = decodeURIComponent(value);
if (gatherArrays && key.endsWith('[]')) {
const decodedKey = decodeURIComponent(key.slice(0, -2));
if (!Array.isArray(accumulator[decodedKey])) {
accumulator[decodedKey] = [];
}
accumulator[decodedKey].push(decodedValue);
} else {
accumulator[decodeURIComponent(key)] = decodedValue;
}
return accumulator;
}, {});
}
......
......@@ -616,6 +616,35 @@ describe('URL utility', () => {
expect(urlUtils.queryToObject(searchQuery)).toEqual({ one: '1', two: '2' });
});
describe('with gatherArrays=false', () => {
it('overwrites values with the same array-key and does not change the key', () => {
const searchQuery = '?one[]=1&one[]=2&two=2&two=3';
expect(urlUtils.queryToObject(searchQuery)).toEqual({ 'one[]': '2', two: '3' });
});
});
describe('with gatherArrays=true', () => {
const options = { gatherArrays: true };
it('gathers only values with the same array-key and strips `[]` from the key', () => {
const searchQuery = '?one[]=1&one[]=2&two=2&two=3';
expect(urlUtils.queryToObject(searchQuery, options)).toEqual({ one: ['1', '2'], two: '3' });
});
it('overwrites values with the same array-key name', () => {
const searchQuery = '?one=1&one[]=2&two=2&two=3';
expect(urlUtils.queryToObject(searchQuery, options)).toEqual({ one: ['2'], two: '3' });
});
it('overwrites values with the same key name', () => {
const searchQuery = '?one[]=1&one=2&two=2&two=3';
expect(urlUtils.queryToObject(searchQuery, options)).toEqual({ one: '2', two: '3' });
});
});
});
describe('objectToQuery', () => {
......
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