Created helper function to evolve a query string based on an object

This commit is contained in:
Alejandro Celaya 2021-11-07 11:22:29 +01:00
parent 109baef828
commit a2421ee2d3
2 changed files with 15 additions and 1 deletions

View file

@ -3,3 +3,6 @@ import qs from 'qs';
export const parseQuery = <T>(search: string) => qs.parse(search, { ignoreQueryPrefix: true }) as unknown as T; export const parseQuery = <T>(search: string) => qs.parse(search, { ignoreQueryPrefix: true }) as unknown as T;
export const stringifyQuery = (query: any): string => qs.stringify(query, { arrayFormat: 'brackets' }); export const stringifyQuery = (query: any): string => qs.stringify(query, { arrayFormat: 'brackets' });
export const evolveStringifiedQuery = (currentQuery: string, extra: any): string =>
stringifyQuery({ ...parseQuery(currentQuery), ...extra });

View file

@ -1,4 +1,4 @@
import { parseQuery, stringifyQuery } from '../../../src/utils/helpers/query'; import { evolveStringifiedQuery, parseQuery, stringifyQuery } from '../../../src/utils/helpers/query';
describe('query', () => { describe('query', () => {
describe('parseQuery', () => { describe('parseQuery', () => {
@ -22,4 +22,15 @@ describe('query', () => {
expect(stringifyQuery(queryObj)).toEqual(expectedResult); 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);
});
});
}); });