-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
MethodMiddleware.js
78 lines (62 loc) · 2.35 KB
/
MethodMiddleware.js
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
/** @typedef {import('../types').HttpTransaction} HttpTransaction */
/** @typedef {import('../types').MiddlewareFunction} MiddlewareFunction */
/** @typedef {import('../types').RequestMethod} RequestMethod */
/** @typedef {RegExp|RequestMethod} MethodEntry */
/**
* @typedef {Object} MethodMiddlewareOptions
* @prop {MethodEntry|MethodEntry[]} method
*/
export default class MethodMiddleware {
/** @param {MethodMiddlewareOptions|MethodEntry|MethodEntry[]} options */
constructor(options) {
if (Array.isArray(options)) {
this.method = options;
} else if (typeof options === 'string' || options instanceof RegExp) {
this.method = [options];
} else {
this.method = Array.isArray(options.method) ? options.method : [options.method];
}
}
/** @type {Map<MethodEntry, MethodMiddleware>} */
static cache = new Map();
/**
* @param {RequestMethod} method
* @param {RegExp | string} input
* @return {boolean}
*/
static test(method, input) {
if (typeof input === 'string') {
return method === input;
}
return input.test(method) === true;
}
/** @type {MiddlewareFunction} */
execute({ request }) {
for (const method of this.method) {
if (MethodMiddleware.test(request.method, method)) {
return true;
}
}
return false;
}
/** @type {MiddlewareFunction} */
static CONNECT({ request }) { return request.method === 'CONNECT'; }
/** @type {MiddlewareFunction} */
static DELETE({ request }) { return request.method === 'DELETE'; }
/** @type {MiddlewareFunction} */
static HEADORGET({ request }) { return request.method === 'HEAD' || request.method === 'GET'; }
/** @type {MiddlewareFunction} */
static GET({ request }) { return request.method === 'GET'; }
/** @type {MiddlewareFunction} */
static OPTIONS({ request }) { return request.method === 'OPTIONS'; }
/** @type {MiddlewareFunction} */
static HEAD({ request }) { return request.method === 'HEAD'; }
/** @type {MiddlewareFunction} */
static PATCH({ request }) { return request.method === 'PATCH'; }
/** @type {MiddlewareFunction} */
static POST({ request }) { return request.method === 'POST'; }
/** @type {MiddlewareFunction} */
static PUT({ request }) { return request.method === 'PUT'; }
/** @type {MiddlewareFunction} */
static TRACE({ request }) { return request.method === 'TRACE'; }
}