1
1
const Layer = require ( 'express/lib/router/layer' ) ;
2
+ const Router = require ( 'express/lib/router' ) ;
2
3
3
- function copyOldProps ( oldFn , newFn ) {
4
+ const last = ( arr = [ ] ) => arr [ arr . length - 1 ] ;
5
+ const noop = Function . prototype ;
6
+
7
+ function copyFnProps ( oldFn , newFn ) {
4
8
Object . keys ( oldFn ) . forEach ( ( key ) => {
5
9
newFn [ key ] = oldFn [ key ] ;
6
10
} ) ;
7
11
return newFn ;
8
12
}
9
13
10
- function wrapErrorMiddleware ( fn ) {
11
- const newFn = ( err , req , res , next ) => {
12
- const ret = fn . call ( this , err , req , res , next ) ;
13
-
14
- if ( ret && ret . catch ) {
15
- ret . catch ( innerErr => next ( innerErr ) ) ;
16
- }
17
-
14
+ function wrap ( fn ) {
15
+ const newFn = function newFn ( ...args ) {
16
+ const ret = fn . apply ( this , args ) ;
17
+ const next = ( args . length === 5 ? args [ 2 ] : last ( args ) ) || noop ;
18
+ if ( ret && ret . catch ) ret . catch ( err => next ( err ) ) ;
18
19
return ret ;
19
20
} ;
20
- return copyOldProps ( fn , newFn ) ;
21
+ Object . defineProperty ( newFn , 'length' , {
22
+ value : fn . length ,
23
+ writable : false ,
24
+ } ) ;
25
+ return copyFnProps ( fn , newFn ) ;
21
26
}
22
27
23
- function wrap ( fn ) {
24
- const newFn = ( req , res , next ) => {
25
- const ret = fn . call ( this , req , res , next ) ;
26
-
27
- if ( ret && ret . catch ) {
28
- ret . catch ( ( err ) => {
29
- next ( err ) ;
30
- } ) ;
31
- }
32
-
33
- return ret ;
28
+ function patchRouterParam ( ) {
29
+ const originalParam = Router . prototype . constructor . param ;
30
+ Router . prototype . constructor . param = function param ( name , fn ) {
31
+ fn = wrap ( fn ) ;
32
+ return originalParam . call ( this , name , fn ) ;
34
33
} ;
35
- return copyOldProps ( fn , newFn ) ;
36
34
}
37
35
38
36
Object . defineProperty ( Layer . prototype , 'handle' , {
@@ -41,13 +39,9 @@ Object.defineProperty(Layer.prototype, 'handle', {
41
39
return this . __handle ;
42
40
} ,
43
41
set ( fn ) {
44
- // Bizarre, but Express checks for 4 args to detect error middleware: https://github.com/expressjs/express/blob/master/lib/router/layer.js
45
- if ( fn . length === 4 ) {
46
- fn = wrapErrorMiddleware ( fn ) ;
47
- } else {
48
- fn = wrap ( fn ) ;
49
- }
50
-
42
+ fn = wrap ( fn ) ;
51
43
this . __handle = fn ;
52
44
} ,
53
45
} ) ;
46
+
47
+ patchRouterParam ( ) ;
0 commit comments