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

qss.ts

85 lines2.5 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 */
25/** Encode a plain object into a URL query string using URLSearchParams. */
26export function encode(
27 obj: Record<string, any>,
28 stringify: (value: any) => string = String,
29): string {
30 const result = new URLSearchParams()
31​
32 for (const key in obj) {
33 const val = obj[key]
34 if (val !== undefined) {
35 result.set(key, stringify(val))
36 }
37 }
38​
39 return result.toString()
41​
42/**
43 * Converts a string value to its appropriate type (string, number, boolean).
44 * @param mix - The string value to convert.
45 * @returns The converted value.
46 * @example
47 * // Example input: toValue("123")
48 * // Expected output: 123
49 */
50/** Convert a string into a primitive boolean/number when possible. */
51function toValue(str: unknown) {
52 if (!str) return ''
53​
54 if (str === 'false') return false
55 if (str === 'true') return true
56 return +str * 0 === 0 && +str + '' === str ? +str : str
58​
59/**
60 * Decodes a query string into an object.
61 * @param str - The query string to decode.
62 * @returns The decoded key-value pairs in an object format.
63 * @example
64 * // Example input: decode("token=foo&key=value")
65 * // Expected output: { "token": "foo", "key": "value" }
66 */
67/** Decode a URL query string into an object with basic type coercion. */
68export function decode(str: any): any {
69 const searchParams = new URLSearchParams(str)
70​
71 const result: Record<string, unknown> = {}
72​
73 for (const [key, value] of searchParams.entries()) {
74 const previousValue = result[key]
75 if (previousValue == null) {
76 result[key] = toValue(value)
77 } else if (Array.isArray(previousValue)) {
78 previousValue.push(toValue(value))
79 } else {
80 result[key] = [previousValue, toValue(value)]
81 }
82 }
83​
84 return result