Skip to content

Commit

Permalink
feat: added new parseQueryString method.
Browse files Browse the repository at this point in the history
  • Loading branch information
BowlingX committed Apr 21, 2022
1 parent 620c942 commit ec18768
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
34 changes: 34 additions & 0 deletions src/__tests__/static.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
23 changes: 21 additions & 2 deletions src/lib/store.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -294,5 +294,24 @@ export const factoryParameters = <T extends object>(
)
}

return { useQuery, createQueryString }
const parseQueryString = (
query: string,
initialValues?: Partial<T> | null
): Partial<T> => {
const thisInitialValues =
typeof initialValues === 'undefined'
? memCreateInitialValues(defaultInitialValues)
: initialValues
return produce({}, (draft: Draft<T>) => {
applyFlatConfigToState(
flatConfig,
parse(query),
ns,
draft as T,
thisInitialValues as T
)
})
}

return { useQuery, createQueryString, parseQueryString }
}

0 comments on commit ec18768

Please sign in to comment.