@plugola/query-params
Parses search query parameters
Examples
Strings
parseQueryParams('?foo=bar&mung=face')
// { foo: 'bar', mung: 'face' }
Booleans
parseQueryParams('foo&!bar')
// { foo: true, bar: false }
Arrays
parseQueryParams('foo[]=foo,bar')
// { foo: ['foo', 'bar'] }
Prepending to arrays
parseQueryParams('foo[^]=bar,face', { into: { foo: ['mung'] } })
// { foo: ['bar', 'face', 'mung'] }
Appending to arrays
parseQueryParams('foo[+]=bar,face', { into: { foo: ['mung'] } })
// { foo: ['mung', 'bar', 'face'] }
Subtracting from arrays
parseQueryParams('foo[-]=mung', { into: { foo: ['bar', 'mung'] } })
// { foo: ['bar'] }
Flags
parseQueryParams('foo{x}=mung,!face')
/* {
foo: { mung: true, face: false }
} */
JSON
parseQueryParams('foo{}={"bar": [1, 2]}')
/* {
foo: {
bar: [1, 2]
}
} */
Merge query params in to an existing object
const config = { foo: '' }
parseQueryParams('cfg.foo=bar', {
// merge in to the `config` property
into: config,
// ... but only use query params that start with `cfg.`
filter: (key) => key.startsWith('cfg.'),
// ... and remove `cfg.` from the property name
amendKey: (key) => key.substr(4),
})
// { foo: 'bar' }
// Or achieving a similar thing with `set` prop.
parseQueryParams('cfg.foo=bar', {
into: config,
set: (queryParams, key, value) =>
key.startsWith('cfg.')
? { ...queryParams, [key.substr(4)]: value }
: queryParams,
})