-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
query.ts
74 lines (69 loc) · 2.13 KB
/
query.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import {
encode,
form as encodeForm,
simple as encodeSimple,
encodeReserved,
} from "./util";
/**
* Join params using an ampersand and prepends a questionmark if not empty.
*/
export function query(...params: string[]) {
const s = params.filter(Boolean).join("&");
return s && `?${s}`;
}
/**
* Serializes nested objects according to the `deepObject` style specified in
* https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#style-values
*/
export function deep(
params: Record<string, any>,
[k, v] = encodeReserved
): string {
const qk = encode([(s) => s, k]);
const qv = encode([(s) => s, v]);
// don't add index to arrays
// https://github.com/expressjs/body-parser/issues/289
const visit = (obj: any, prefix = ""): string =>
Object.entries(obj)
.filter(([, v]) => v !== undefined)
.map(([prop, v]) => {
const index = Array.isArray(obj) ? "" : prop;
const key = prefix ? qk`${prefix}[${index}]` : prop;
if (typeof v === "object") {
return visit(v, key);
}
return qv`${key}=${v}`;
})
.join("&");
return visit(params);
}
/**
* Property values of type array or object generate separate parameters
* for each value of the array, or key-value-pair of the map.
* For other types of properties this property has no effect.
* See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#encoding-object
*/
export function explode(
params: Record<string, any>,
encoders = encodeReserved
): string {
const q = encode(encoders);
return Object.entries(params)
.filter(([, value]) => value !== undefined)
.map(([name, value]) => {
if (Array.isArray(value)) {
return value.map((v) => q`${name}=${v}`).join("&");
}
if (typeof value === "object") {
return explode(value, encoders);
}
return q`${name}=${value}`;
})
.join("&");
}
export const form = encodeForm();
export const formPipe = encodeForm("|");
export const formSpace = encodeForm("%20");
export const simple = encodeSimple();
export const pipe = encodeSimple("|");
export const space = encodeSimple("%20");