forked from vercel/next.js
/
querystring.ts
54 lines (50 loc) · 1.39 KB
/
querystring.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import type { ParsedUrlQuery } from 'querystring'
export function searchParamsToUrlQuery(
searchParams: URLSearchParams
): ParsedUrlQuery {
const query: ParsedUrlQuery = {}
searchParams.forEach((value, key) => {
if (typeof query[key] === 'undefined') {
query[key] = value
} else if (Array.isArray(query[key])) {
;(query[key] as string[]).push(value)
} else {
query[key] = [query[key] as string, value]
}
})
return query
}
function stringifyUrlQueryParam(param: string): string {
if (
typeof param === 'string' ||
(typeof param === 'number' && !isNaN(param)) ||
typeof param === 'boolean'
) {
return String(param)
} else {
return ''
}
}
export function urlQueryToSearchParams(
urlQuery: ParsedUrlQuery
): URLSearchParams {
const result = new URLSearchParams()
Object.entries(urlQuery).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((item) => result.append(key, stringifyUrlQueryParam(item)))
} else {
result.set(key, stringifyUrlQueryParam(value))
}
})
return result
}
export function assign(
target: URLSearchParams,
...searchParamsList: URLSearchParams[]
): URLSearchParams {
searchParamsList.forEach((searchParams) => {
Array.from(searchParams.keys()).forEach((key) => target.delete(key))
searchParams.forEach((value, key) => target.append(key, value))
})
return target
}