@@ -3,12 +3,16 @@ const bodyParser = require('body-parser')
3
3
const chalk = require ( 'chalk' )
4
4
5
5
function registerRoutes ( app ) {
6
+ let mockStartIndex
6
7
const { default : mocks } = require ( './index.js' )
7
8
for ( const mock of mocks ) {
8
9
app [ mock . type ] ( mock . url , mock . response )
10
+ mockStartIndex = app . _router . stack . length
9
11
}
12
+ const mockRoutesLength = Object . keys ( mocks ) . length
10
13
return {
11
- mockRoutesLength : Object . keys ( mocks ) . length
14
+ mockRoutesLength : mockRoutesLength ,
15
+ mockStartIndex : mockStartIndex - mockRoutesLength
12
16
}
13
17
}
14
18
@@ -20,28 +24,6 @@ function unregisterRoutes() {
20
24
} )
21
25
}
22
26
23
- function getPath ( path ) {
24
- var match = path . toString ( )
25
- . replace ( '\\/?' , '' )
26
- . replace ( '(?=\\/|$)' , '$' )
27
- . match ( / ^ \/ \^ ( (?: \\ [ . * + ? ^ $ { } ( ) | [ \] \\ \/ ] | [ ^ . * + ? ^ $ { } ( ) | [ \] \\ \/ ] ) * ) \$ \/ / )
28
- return match
29
- ? match [ 1 ] . replace ( / \\ ( .) / g, '$1' ) . split ( '/' )
30
- : path . toString ( )
31
- }
32
-
33
- function getMockRoutesIndex ( app ) {
34
- for ( let index = 0 ; index <= app . _router . stack . length ; index ++ ) {
35
- const r = app . _router . stack [ index ]
36
- if ( r . route && r . route . path ) {
37
- const path = getPath ( r . route . path )
38
- if ( path . includes ( 'mock' ) ) {
39
- return index
40
- }
41
- }
42
- }
43
- }
44
-
45
27
module . exports = app => {
46
28
// es6 polyfill
47
29
require ( '@babel/register' )
@@ -53,7 +35,9 @@ module.exports = app => {
53
35
extended : true
54
36
} ) )
55
37
56
- const { mockRoutesLength } = registerRoutes ( app )
38
+ const mockRoutes = registerRoutes ( app )
39
+ var mockRoutesLength = mockRoutes . mockRoutesLength
40
+ var mockStartIndex = mockRoutes . mockStartIndex
57
41
58
42
// watch files, hot reload mock server
59
43
chokidar . watch ( ( './mock' ) , {
@@ -62,16 +46,15 @@ module.exports = app => {
62
46
ignoreInitial : true
63
47
} ) . on ( 'all' , ( event , path ) => {
64
48
if ( event === 'change' || event === 'add' ) {
65
- // find mock routes stack index
66
- const index = getMockRoutesIndex ( app )
67
-
68
49
// remove mock routes stack
69
- app . _router . stack . splice ( index , mockRoutesLength )
50
+ app . _router . stack . splice ( mockStartIndex , mockRoutesLength )
70
51
71
52
// clear routes cache
72
53
unregisterRoutes ( )
73
54
74
- registerRoutes ( app )
55
+ const mockRoutes = registerRoutes ( app )
56
+ mockRoutesLength = mockRoutes . mockRoutesLength
57
+ mockStartIndex = mockRoutes . mockStartIndex
75
58
76
59
console . log ( chalk . magentaBright ( `\n > Mock Server hot reload success! changed ${ path } ` ) )
77
60
}
0 commit comments