1
1
const chokidar = require ( 'chokidar' ) ;
2
2
const bodyParser = require ( 'body-parser' ) ;
3
3
const chalk = require ( 'chalk' ) ;
4
+ const path = require ( 'path' ) ;
5
+
6
+ const mockDir = path . join ( process . cwd ( ) , 'mock' ) ;
4
7
5
8
function registerRoutes ( app ) {
6
9
let mockLastIndex ;
@@ -18,15 +21,15 @@ function registerRoutes(app) {
18
21
19
22
function unregisterRoutes ( ) {
20
23
Object . keys ( require . cache ) . forEach ( ( i ) => {
21
- if ( i . includes ( '/mock' ) ) {
24
+ if ( i . includes ( mockDir ) ) {
22
25
delete require . cache [ require . resolve ( i ) ] ;
23
26
}
24
27
} ) ;
25
28
}
26
29
27
30
module . exports = ( app ) => {
28
31
// es6 polyfill
29
- require ( '@babel/register' ) ( { extensions : [ '.ts' , '.tsx' , '.js' , '.jsx' ] } ) ;
32
+ require ( '@babel/register' ) ( { extensions : [ '.ts' , '.tsx' , '.js' , '.jsx' ] } ) ;
30
33
// parse app.body
31
34
// https://expressjs.com/en/4x/api.html#req.body
32
35
app . use ( bodyParser . json ( ) ) ;
@@ -39,23 +42,26 @@ module.exports = (app) => {
39
42
let mockStartIndex = mockRoutes . mockStartIndex ;
40
43
41
44
// watch files, hot reload mock server
42
- chokidar . watch ( ( './mock' ) , {
45
+ chokidar . watch ( mockDir , {
43
46
ignored : 'mock/mockServer.ts' ,
44
- persistent : true ,
45
47
ignoreInitial : true
46
48
} ) . on ( 'all' , ( event , path ) => {
47
49
if ( event === 'change' || event === 'add' ) {
48
- // remove mock routes stack
49
- app . _router . stack . splice ( mockStartIndex , mockRoutesLength ) ;
50
+ try {
51
+ // remove mock routes stack
52
+ app . _router . stack . splice ( mockStartIndex , mockRoutesLength ) ;
50
53
51
- // clear routes cache
52
- unregisterRoutes ( ) ;
54
+ // clear routes cache
55
+ unregisterRoutes ( ) ;
53
56
54
- const mockRoutes = registerRoutes ( app ) ;
55
- mockRoutesLength = mockRoutes . mockRoutesLength ;
56
- mockStartIndex = mockRoutes . mockStartIndex ;
57
+ const mockRoutes = registerRoutes ( app ) ;
58
+ mockRoutesLength = mockRoutes . mockRoutesLength ;
59
+ mockStartIndex = mockRoutes . mockStartIndex ;
57
60
58
- console . log ( chalk . magentaBright ( `\n > Mock Server hot reload success! changed ${ path } ` ) ) ;
61
+ console . log ( chalk . magentaBright ( `\n > Mock Server hot reload success! changed ${ path } ` ) ) ;
62
+ } catch ( error ) {
63
+ console . log ( chalk . redBright ( error ) ) ;
64
+ }
59
65
}
60
66
} ) ;
61
67
} ;
0 commit comments