typed-qparam

🔍 Type-safe query parameter manipulation
[!NOTE]
See here for documentation on <=v1 features.
Installation
npm i typed-qparam
Simple Usage
Passing a query parameter key to the qparam
function returns the accessor for that value.
import { extract } from 'typed-qparam'
const qparam = extract(new URL('https://example.com/?foo=bar'))
const foo = qparam('foo')
console.log(foo.get())
const url = foo.set('baz')
console.log(url.href)
Typed Param
By passing a conversion function as the second argument, you can obtain a value converted to any type.
See ts-serde for more information on type guard.
import { extract } from 'typed-qparam'
import { number } from 'typed-qparam/serde'
const qparam = extract(new URL('https://example.com/?num=123'))
const num = qparam('num', {
stringify: (value) => value.toString(),
parse: (str) => parseInt(str)
})
console.log(num.get())
const dist = num.set(456)
Prepared Converter
You can also use the prepared converters in typed-qparam/serde
.
See ts-serde for more information on type guard
import { extract } from 'typed-qparam'
import { number, boolean, enums } from 'typed-qparam/serde'
const qparam = extract(
new URL('https://example.com/?num=123&bool=true&enumerate=b')
)
const num = qparam('num', number)
const bool = qparam('bool', boolean)
const enumerate = qparam(
'enumerate',
enums(
['a', 'b', 'c'],
'a'
)
)
Array Param
Sometimes you need to handle query parameters with multiple values in the same key, such as ?str=hello&str=world
.
With typed-qparam
, you can treat this as an array.
import { extract, array } from 'svelte-qparam'
import { string, number } from 'svelte-qparam/serde'
const qparam = extract(new URL('https://example.com/?str=hello&str=world'))
const str = qparam('str', array())
const num = qparam('num', array(number))
console.log(str.get())
str.set(['foo', 'bar', 'baz'])
License
MIT