Skip to content

Commit

Permalink
feat: 🎸 在内部自己管理process信号量的关闭行为
Browse files Browse the repository at this point in the history
  • Loading branch information
倪俊杰 committed Nov 11, 2021
1 parent ab11979 commit ee3105e
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 15 deletions.
16 changes: 4 additions & 12 deletions demo/mockServer/server.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const path = require('path')
// mock文件的根目录
const mockRoot = path.join(__dirname, './mock')
// require koa-mock-switch
const KoaMockSwitch = require('../../lib/index.js')
// require mock-master
const MockMaster = require('../../lib/index.js')
// mock管理列表
const mockSwitchMap = require('./mockSwitchMap.js')
/**
Expand All @@ -13,20 +13,12 @@ const mockSwitchMap = require('./mockSwitchMap.js')
* @param apiPrefix 客户端请求api的前缀,比如'/api/kitty.json',apiPrefix就是'/api'
* @param apiSuffix 客户端请求api的后缀,比如'/api/kitty.json',apiSuffix就是'.json'
*/
const mock = new KoaMockSwitch({
const mock = new MockMaster({
root: mockRoot,
port: 7878,
switchMap: mockSwitchMap,
apiPrefix: '/api',
apiSuffix: '.htm'
})
// 启动mock服务
mock.start()

// nodemon会command+c终止终端都无法关闭mock进程
// 所以需要进程接受信号来调用koa-mock-switch接口来关闭
;['SIGINT', 'SIGTERM'].forEach(signal => {
process.on(signal, () => {
mock.stop()
})
})
mock.start()
27 changes: 25 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ const send = require('koa-send')
const Koa = require('koa')
const fs = require('fs')
const processMock = require('./processMock')
const { logger } = require('./utils/index')
// 使用router
const Router = require('koa-router')
const Boom = require('boom')
const koaBody = require('koa-body')
const app = new Koa()
const router = new Router()

app.use(router.routes())
app.use(router.allowedMethods({
throw: true,
Expand Down Expand Up @@ -45,14 +47,35 @@ class KoaMockSwitch {
app.use(this._mockDataByFileMiddware.bind(this))
// 错误打印
app.on('error', (err, ctx) => {
console.log('server error', err, ctx)
logger.error(`${ctx.url} error\n${err.stack}`)
})
this._listen()
}

_listen() {
// 注意:这里的端口要和webpack里devServer的端口对应
this._server = app.listen(this.port)

this._server.on('error', (err) => {
logger.error(err.message)
})
// 监听关闭信号
this._watchProcessStop()
}

_watchProcessStop() {
// 信号量含义:http://nodejs.cn/api/process/signal_events.html
['SIGINT', 'SIGTERM', 'SIGHUP'].forEach(signal => {
process.on(signal, () => {
this._stop()
})
})
}

stop() {
_stop() {
this._server && this._server.close(() => {
console.log()
logger.done('mock-master stopped')
process.exit(0)
})
}
Expand Down
5 changes: 5 additions & 0 deletions lib/utils/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[
'logger',
].forEach(m => {
Object.assign(exports, require(`./${m}`))
})
35 changes: 35 additions & 0 deletions lib/utils/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const chalk = require('chalk')

const error = (msg) => {
console.error(_format(chalk.bgRed(' ERROR '), chalk.red(msg)))
if (msg instanceof Error) {
console.error(msg.stack)
}
}

const info = (msg) => {
console.warn(_format(chalk.bgBlue.black(' INFO '), chalk.blue(msg)))
}

const warn = (msg) => {
console.warn(_format(chalk.bgYellow.black(' WARN '), chalk.yellow(msg)))
}

const done = (msg) => {
console.log(_format(chalk.bgGreen.black(' DONE '), chalk.green(msg)))
}

function _format (label, msg) {
return msg.split('\n').map((line, index) => {
return index === 0
? `${label} ${line}`
: line
}).join('\n')
}

exports.logger = {
error,
info,
warn,
done,
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"lib"
],
"scripts": {
"mock": "nodemon -q --inspect ./demo/mockServer/server.js",
"mock": "nodemon -q ./demo/mockServer/server.js",
"prepare": "husky install",
"demo": "webpack-dev-server --open --config ./demo/webpack.config",
"commit": "git-cz",
Expand Down

0 comments on commit ee3105e

Please sign in to comment.