Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

qss.ts

81 lines2.3 KB

1/**
2 * Program is a reimplementation of the `qss` package:
3 * Copyright (c) Luke Edwards luke.edwards05@gmail.com, MIT License
4 * https://github.com/lukeed/qss/blob/master/license.md
5 *
6 * This reimplementation uses modern browser APIs
7 * (namely URLSearchParams) and TypeScript while still
8 * maintaining the original functionality and interface.
9 *
10 * Update: this implementation has also been mangled to
11 * fit exactly our use-case (single value per key in encoding).
12 */
13​
14/**
15 * Encodes an object into a query string.
16 * @param obj - The object to encode into a query string.
17 * @param stringify - An optional custom stringify function.
18 * @returns The encoded query string.
19 * @example
20 * ```
21 * // Example input: encode({ token: 'foo', key: 'value' })
22 * // Expected output: "token=foo&key=value"
23 * ```
24 */
25export function encode(
26 obj: Record<string, any>,
27 stringify: (value: any) => string = String,
28): string {
29 let result: URLSearchParams | undefined
30​
31 for (const key in obj) {
32 const val = obj[key]
33 if (val !== undefined) {
34 ;(result ||= new URLSearchParams()).set(key, stringify(val))
35 }
36 }
37​
38 return result ? result.toString() : ''
40​
41/**
42 * Converts a string value to its appropriate type (string, number, boolean).
43 * @param mix - The string value to convert.
44 * @returns The converted value.
45 * @example
46 * // Example input: toValue("123")
47 * // Expected output: 123
48 */
49function toValue(str: unknown) {
50 if (!str) return ''
51​
52 if (str === 'false') return false
53 if (str === 'true') return true
54 return +str * 0 === 0 && +str + '' === str ? +str : str
56/**
57 * Decodes a query string into an object.
58 * @param str - The query string to decode.
59 * @returns The decoded key-value pairs in an object format.
60 * @example
61 * // Example input: decode("token=foo&key=value")
62 * // Expected output: { "token": "foo", "key": "value" }
63 */
64export function decode(str: any): any {
65 const searchParams = new URLSearchParams(str)
66​
67 const result: Record<string, unknown> = Object.create(null)
68​
69 for (const [key, value] of searchParams.entries()) {
70 const previousValue = result[key]
71 if (previousValue == null) {
72 result[key] = toValue(value)
73 } else if (Array.isArray(previousValue)) {
74 previousValue.push(toValue(value))
75 } else {
76 result[key] = [previousValue, toValue(value)]
77 }
78 }
79​
80 return result