Blame view

mock/mock-server.js 1.8 KB
80a28914e   吉鹏   init
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
  const chokidar = require('chokidar')
  const bodyParser = require('body-parser')
  const chalk = require('chalk')
  const path = require('path')
  
  const mockDir = path.join(process.cwd(), 'mock')
  
  function registerRoutes(app) {
    let mockLastIndex
    const { default: mocks } = require('./index.js')
    for (const mock of mocks) {
      app[mock.type](mock.url, mock.response)
      mockLastIndex = app._router.stack.length
    }
    const mockRoutesLength = Object.keys(mocks).length
    return {
      mockRoutesLength: mockRoutesLength,
      mockStartIndex: mockLastIndex - mockRoutesLength
    }
  }
  
  function unregisterRoutes() {
    Object.keys(require.cache).forEach(i => {
      if (i.includes(mockDir)) {
        delete require.cache[require.resolve(i)]
      }
    })
  }
  
  module.exports = app => {
    // es6 polyfill
    require('@babel/register')
  
    // parse app.body
    // https://expressjs.com/en/4x/api.html#req.body
    app.use(bodyParser.json())
    app.use(bodyParser.urlencoded({
      extended: true
    }))
  
    const mockRoutes = registerRoutes(app)
    var mockRoutesLength = mockRoutes.mockRoutesLength
    var mockStartIndex = mockRoutes.mockStartIndex
  
    // watch files, hot reload mock server
    chokidar.watch(mockDir, {
      ignored: /mock-server/,
      ignoreInitial: true
    }).on('all', (event, path) => {
      if (event === 'change' || event === 'add') {
        try {
          // remove mock routes stack
          app._router.stack.splice(mockStartIndex, mockRoutesLength)
  
          // clear routes cache
          unregisterRoutes()
  
          const mockRoutes = registerRoutes(app)
          mockRoutesLength = mockRoutes.mockRoutesLength
          mockStartIndex = mockRoutes.mockStartIndex
  
          console.log(chalk.magentaBright(`
   > Mock Server hot reload success! changed  ${path}`))
        } catch (error) {
d7d9c38c2   Adam   auto commit the c...
65
          console.log(chalk.redBright(error))
80a28914e   吉鹏   init
66
67
68
69
        }
      }
    })
  }