-
Notifications
You must be signed in to change notification settings - Fork 0
/
EndpointMatcher.ts
76 lines (69 loc) · 1.61 KB
/
EndpointMatcher.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
import {
Matcher,
} from './Matcher'
import {
MatchResult,
} from './MatchResult'
import {
Method,
MethodMatchResult,
MethodMatcher,
} from './MethodMatcher'
import {
AndMatcher,
} from './AndMatcher'
import {
RegExpExecGroupArray,
RegExpUrlMatchResult,
RegExpUrlMatcher,
} from './RegExpUrlMatcher'
// waiting for
// https://github.com/microsoft/TypeScript/issues/10571
// https://github.com/microsoft/TypeScript/pull/26349
// to resolve http method
export interface EndpointMatcherInput {
req: {
url: string
method: string
}
}
export type EndpointMatchResult<R extends object> =
MatchResult<{
method: Method
match: RegExpExecGroupArray<R>
}>
/**
* higher order matcher which is combine matching of method
* with regular expression
*/
export class EndpointMatcher<
R extends object,
P extends EndpointMatcherInput = EndpointMatcherInput
>
implements Matcher<EndpointMatchResult<R>, P> {
private readonly matcher: AndMatcher<MethodMatchResult<[Method]>, RegExpUrlMatchResult<R>, P, P>
constructor(methods: Method | Method[], url: RegExp) {
this.match = this.match.bind(this)
this.matcher = new AndMatcher([
new MethodMatcher(Array.isArray(methods) ? methods : [methods]),
new RegExpUrlMatcher<R, P>([url]),
])
}
match(params: EndpointMatcherInput): EndpointMatchResult<R> {
// @ts-expect-error
const result = this.matcher.match(params)
if (result.matched) {
const [methodResult, urlResult] = result.result.and
return {
matched: true,
result: {
method: methodResult.result.method,
match: urlResult.result.match,
},
}
}
return {
matched: false,
}
}
}