@@ -3,12 +3,16 @@ const bodyParser = require('body-parser')
33const chalk = require ( 'chalk' )
44
55function registerRoutes ( app ) {
6+ let mockStartIndex
67 const { default : mocks } = require ( './index.js' )
78 for ( const mock of mocks ) {
89 app [ mock . type ] ( mock . url , mock . response )
10+ mockStartIndex = app . _router . stack . length
911 }
12+ const mockRoutesLength = Object . keys ( mocks ) . length
1013 return {
11- mockRoutesLength : Object . keys ( mocks ) . length
14+ mockRoutesLength : mockRoutesLength ,
15+ mockStartIndex : mockStartIndex - mockRoutesLength
1216 }
1317}
1418
@@ -20,28 +24,6 @@ function unregisterRoutes() {
2024 } )
2125}
2226
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-
4527module . exports = app => {
4628 // es6 polyfill
4729 require ( '@babel/register' )
@@ -53,7 +35,9 @@ module.exports = app => {
5335 extended : true
5436 } ) )
5537
56- const { mockRoutesLength } = registerRoutes ( app )
38+ const mockRoutes = registerRoutes ( app )
39+ var mockRoutesLength = mockRoutes . mockRoutesLength
40+ var mockStartIndex = mockRoutes . mockStartIndex
5741
5842 // watch files, hot reload mock server
5943 chokidar . watch ( ( './mock' ) , {
@@ -62,16 +46,15 @@ module.exports = app => {
6246 ignoreInitial : true
6347 } ) . on ( 'all' , ( event , path ) => {
6448 if ( event === 'change' || event === 'add' ) {
65- // find mock routes stack index
66- const index = getMockRoutesIndex ( app )
67-
6849 // remove mock routes stack
69- app . _router . stack . splice ( index , mockRoutesLength )
50+ app . _router . stack . splice ( mockStartIndex , mockRoutesLength )
7051
7152 // clear routes cache
7253 unregisterRoutes ( )
7354
74- registerRoutes ( app )
55+ const mockRoutes = registerRoutes ( app )
56+ mockRoutesLength = mockRoutes . mockRoutesLength
57+ mockStartIndex = mockRoutes . mockStartIndex
7558
7659 console . log ( chalk . magentaBright ( `\n > Mock Server hot reload success! changed ${ path } ` ) )
7760 }
0 commit comments