-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExactQueryMatcher.ts
105 lines (96 loc) · 2.29 KB
/
ExactQueryMatcher.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import Url from 'urlite'
import {
Matcher,
} from './Matcher'
import {
MatchResult,
} from './MatchResult'
export interface ExactQueryMatcherInput {
req: {
url: string
}
}
type QueryMatch = { [key: string]: readonly string[] | true | false | undefined }
type QueryResult<T> = {
[P in keyof T]:
T[P] extends true ? string
: T[P] extends false ? never
: T[P] extends undefined ? string | undefined
: T[P] extends readonly string[] ? T[P][number]
: never
}
export type ExactQueryMatchResult<U extends QueryMatch> = MatchResult<{
query: QueryResult<U>
}>
/**
* Match query params
*
* key is a string and value:
* true: must be present
* false: must be absent
* undefined: optional
* 'some string': must be exact value
*/
export class ExactQueryMatcher<U extends QueryMatch, P extends ExactQueryMatcherInput>
implements Matcher<ExactQueryMatchResult<U>, P> {
private readonly listConfig: [string, readonly string[] | true | false | undefined][]
constructor(config: U) {
this.match = this.match.bind(this)
this.listConfig = Object.entries(config)
}
match({ req }: P): ExactQueryMatchResult<U> {
// original URL returns '' if search is empty
const search = Url.parse(req.url).search ?? ''
// parse query string into dict
let params = {} as QueryResult<U>
if (search !== '') {
params = search.substring(1).split(/&/).reduce((acc, parts) => {
const part = parts.split(/=/)
const [key, value] = part
// @ts-ignore
acc[key] = value
return acc
}, params)
}
// validate query params
for (const [key, value] of this.listConfig) {
switch (value) {
// key must be absent
case false:
if (key in params) {
return {
matched: false,
}
}
break
// key must be present with any value
case true:
if (key in params === false) {
return {
matched: false,
}
}
break
// don't care about optional keys
case undefined:
break
// assume string[] and therefore exact key and value
default: {
const paramsValue = params[key] as string | undefined
if (!paramsValue || value.includes(paramsValue) === false) {
return {
matched: false,
}
}
}
}
}
// everything is fine
return {
matched: true,
result: {
query: params,
},
}
}
}