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
export const operatorMap = {
"=": "eq",
">": "gt",
"<": "lt",
"!=": "ne",
">=": "gte",
"<=": "lte",
} as const;
export const reverseOperatorMap = {
eq: "=",
gt: ">",
lt: "<",
ne: "!=",
gte: ">=",
lte: "<=",
};
export type QueryOperator = keyof typeof operatorMap;
export type Operator = typeof operatorMap[QueryOperator];
type OneKeyObject<Op extends string> = { [K in Op]: Record<K, string>[] }[Op];
export type ParamOperation = OneKeyObject<QueryOperator>;
export type ParsedQuery<T extends object = {}> = Record<keyof T, ParamOperation>;
const pairPattern = /([a-zA-Z0-9_-]+)([=!<>]=?|[<>])(.+)/;
export function superchargedQueryParams(url: URL): ParsedQuery {
return decodeURIComponent(url.search)
.slice(1)
.split("&")
.map(part => {
const matches = pairPattern.exec(part);
if (!matches) return null;
const key = matches[1];
const value = matches[3];
const queryOperator = matches[2] as QueryOperator;
const operator = operatorMap[queryOperator];
return { key, operator, value };
})
.filter(Boolean)
.reduce((acc, { key, operator, value }) => {
const existing = acc[key] || [];
existing.push({ [operatorMap[operator]]: value });
acc[key] = existing;
return acc;
}, {});
}
export default superchargedQueryParams;