-
Notifications
You must be signed in to change notification settings - Fork 869
/
Copy pathpath-filter.ts
98 lines (83 loc) · 2.56 KB
/
path-filter.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
import type { Filter } from './types';
import * as isGlob from 'is-glob';
import * as micromatch from 'micromatch';
import * as url from 'url';
import { ERRORS } from './errors';
import type * as http from 'http';
export function matchPathFilter<TReq = http.IncomingMessage>(
pathFilter: Filter<TReq> = '/',
uri: string | undefined,
req: http.IncomingMessage,
): boolean {
// single path
if (isStringPath(pathFilter as string)) {
return matchSingleStringPath(pathFilter as string, uri);
}
// single glob path
if (isGlobPath(pathFilter as string)) {
return matchSingleGlobPath(pathFilter as unknown as string[], uri);
}
// multi path
if (Array.isArray(pathFilter)) {
if (pathFilter.every(isStringPath)) {
return matchMultiPath(pathFilter, uri);
}
if (pathFilter.every(isGlobPath)) {
return matchMultiGlobPath(pathFilter as string[], uri);
}
throw new Error(ERRORS.ERR_CONTEXT_MATCHER_INVALID_ARRAY);
}
// custom matching
if (typeof pathFilter === 'function') {
const pathname = getUrlPathName(uri) as string;
return pathFilter(pathname, req as TReq);
}
throw new Error(ERRORS.ERR_CONTEXT_MATCHER_GENERIC);
}
/**
* @param {String} pathFilter '/api'
* @param {String} uri 'http://example.org/api/b/c/d.html'
* @return {Boolean}
*/
function matchSingleStringPath(pathFilter: string, uri?: string) {
const pathname = getUrlPathName(uri);
return pathname?.indexOf(pathFilter) === 0;
}
function matchSingleGlobPath(pattern: string | string[], uri?: string) {
const pathname = getUrlPathName(uri) as string;
const matches = micromatch([pathname], pattern);
return matches && matches.length > 0;
}
function matchMultiGlobPath(patternList: string | string[], uri?: string) {
return matchSingleGlobPath(patternList, uri);
}
/**
* @param {String} pathFilterList ['/api', '/ajax']
* @param {String} uri 'http://example.org/api/b/c/d.html'
* @return {Boolean}
*/
function matchMultiPath(pathFilterList: string[], uri?: string) {
let isMultiPath = false;
for (const context of pathFilterList) {
if (matchSingleStringPath(context, uri)) {
isMultiPath = true;
break;
}
}
return isMultiPath;
}
/**
* Parses URI and returns RFC 3986 path
*
* @param {String} uri from req.url
* @return {String} RFC 3986 path
*/
function getUrlPathName(uri?: string) {
return uri && url.parse(uri).pathname;
}
function isStringPath(pathFilter: string) {
return typeof pathFilter === 'string' && !isGlob(pathFilter);
}
function isGlobPath(pathFilter: string) {
return isGlob(pathFilter);
}