From a2421ee2d3cdc01f85517d066d932d974153416a Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Sun, 7 Nov 2021 11:22:29 +0100 Subject: [PATCH] Created helper function to evolve a query string based on an object --- src/utils/helpers/query.ts | 3 +++ test/utils/helpers/query.test.ts | 13 ++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/utils/helpers/query.ts b/src/utils/helpers/query.ts index 8c59f6eb..7d378f04 100644 --- a/src/utils/helpers/query.ts +++ b/src/utils/helpers/query.ts @@ -3,3 +3,6 @@ import qs from 'qs'; export const parseQuery = (search: string) => qs.parse(search, { ignoreQueryPrefix: true }) as unknown as T; export const stringifyQuery = (query: any): string => qs.stringify(query, { arrayFormat: 'brackets' }); + +export const evolveStringifiedQuery = (currentQuery: string, extra: any): string => + stringifyQuery({ ...parseQuery(currentQuery), ...extra }); diff --git a/test/utils/helpers/query.test.ts b/test/utils/helpers/query.test.ts index 90969bce..585af91a 100644 --- a/test/utils/helpers/query.test.ts +++ b/test/utils/helpers/query.test.ts @@ -1,4 +1,4 @@ -import { parseQuery, stringifyQuery } from '../../../src/utils/helpers/query'; +import { evolveStringifiedQuery, parseQuery, stringifyQuery } from '../../../src/utils/helpers/query'; describe('query', () => { describe('parseQuery', () => { @@ -22,4 +22,15 @@ describe('query', () => { expect(stringifyQuery(queryObj)).toEqual(expectedResult); }); }); + + describe('evolveStringifiedQuery', () => { + it.each([ + [ '?foo=bar', { baz: 123 }, 'foo=bar&baz=123' ], + [ 'foo=bar', { baz: 123 }, 'foo=bar&baz=123' ], + [ 'foo=bar&baz=hello', { baz: 'world' }, 'foo=bar&baz=world' ], + [ '?', { foo: 'some', bar: 'thing' }, 'foo=some&bar=thing' ], + ])('adds and overwrites params on provided query string', (query, extra, expected) => { + expect(evolveStringifiedQuery(query, extra)).toEqual(expected); + }); + }); });