-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
66 lines (54 loc) · 2.18 KB
/
index.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
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import app = require('express/lib/application')
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import Layer = require('router/lib/layer')
import { flatten } from 'array-flatten'
import methods from 'methods'
import { Request, Response, NextFunction, RequestHandler as ExpressRequestHandler, Application, Router as ExpressRouter, RouterOptions } from 'express'
type PathParams = string | RegExp | Array<string | RegExp>
type RequestHandler = ExpressRequestHandler | Array<ExpressRequestHandler>
type Router = ExpressRouter & {
caseSensitive: RouterOptions['caseSensitive']
strict: RouterOptions['strict']
}
type LayerOptions = {
sensitive?: boolean
strict?: boolean
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noOp = () => {}
const handler = (fn: string, getLayerOpts: () => LayerOptions) => function(this: Application | Router, path: PathParams, ...middleware: RequestHandler[]): void {
const modifiedMiddleware = flatten(middleware).map((_middleware: ExpressRequestHandler) => (req: Request, res: Response, next: NextFunction) => {
const layerOpts = {
...getLayerOpts.call(this),
end: fn !== 'use',
}
const layer = new Layer(path, layerOpts, noOp)
if (layer.match(req.path)) return next()
return _middleware(req, res, next)
})
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const thisFn: (path: PathParams, ...middleware: RequestHandler[]) => void = this[fn].bind(this)
return thisFn(fn !== 'use' ? /.*/ : '/', modifiedMiddleware)
}
for (const fn of ['use', 'all'].concat(methods)) {
app[`${fn}Except`] = handler(fn, function(this: Application) {
return {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
sensitive: this.router.caseSensitive,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
strict: this.router.strict
}
})
ExpressRouter.prototype[`${fn}Except`] = handler(fn, function(this: Router) {
return {
sensitive: this.caseSensitive,
strict: this.strict
}
})
}