diff --git a/src/__tests__/static.ts b/src/__tests__/static.ts new file mode 100644 index 0000000..86492ee --- /dev/null +++ b/src/__tests__/static.ts @@ -0,0 +1,34 @@ +/* tslint:disable:no-expression-statement no-object-mutation */ + +import { factoryParameters } from '../lib/store' +import { pm } from '../lib/utils' +import { serializers } from '../lib/serializers' + +describe('static parseQueryString', () => { + const initialValues = { someParameter: 'test' } + const { parseQueryString } = factoryParameters( + { + someParameter: pm('wow', serializers.string), + }, + initialValues + ) + + it('should parse a query string', () => { + const result = parseQueryString('?wow=nice') + expect(result).toEqual({ someParameter: 'nice' }) + }) + + it('should return defaults if empty', () => { + const result = parseQueryString('') + expect(result).toEqual(initialValues) + }) + it('should return defaults if different string', () => { + const result = parseQueryString('?somethingElse=cool') + expect(result).toEqual(initialValues) + }) + it('should allow to override defaults', () => { + const newDefaults = { someParameter: 'otherDefault' } + const result = parseQueryString('', newDefaults) + expect(result).toEqual(newDefaults) + }) +}) diff --git a/src/lib/store.ts b/src/lib/store.ts index b97cf90..77291f4 100644 --- a/src/lib/store.ts +++ b/src/lib/store.ts @@ -1,7 +1,7 @@ /* tslint:disable:no-expression-statement readonly-array no-shadowed-variable */ import { Draft, enablePatches, produce } from 'immer' import memoizeOne from 'memoize-one' -import { stringify } from 'query-string' +import { stringify, parse } from 'query-string' import { createContext, useCallback, @@ -294,5 +294,24 @@ export const factoryParameters = ( ) } - return { useQuery, createQueryString } + const parseQueryString = ( + query: string, + initialValues?: Partial | null + ): Partial => { + const thisInitialValues = + typeof initialValues === 'undefined' + ? memCreateInitialValues(defaultInitialValues) + : initialValues + return produce({}, (draft: Draft) => { + applyFlatConfigToState( + flatConfig, + parse(query), + ns, + draft as T, + thisInitialValues as T + ) + }) + } + + return { useQuery, createQueryString, parseQueryString } }