UNPKG

1.96 kBJavaScriptView Raw
1const Worker = require('./../class/Worker')
2const startWorkers = require('./../module/startWorkers')
3const getPack = require('./../module/getPack')
4
5/*
6command {
7 app,
8 opt: {
9 timeout,
10 signal
11 }
12}
13*/
14
15module.exports = function restart(config, command) {
16 return new Promise((resolve, reject) => {
17 if (global.isResurrectable) {
18 throw new Error('no apps running')
19 }
20
21 // find old app
22 const app = config.apps.find(app => app.name === command.app)
23
24 if (!app) {
25 throw new Error(`app "${command.app}" not found`)
26 }
27
28 // reload package.json
29 const pack = getPack(app.dir, app.opt, app.env)
30
31 // if name changed
32 const nameChanged = pack.name !== app.name
33 if (nameChanged) {
34 // check name
35 if (config.apps.some(app => app.name === pack.name)) {
36 throw new Error(`new name "${pack.name}" already in use`)
37 }
38
39 // save new app
40 config.apps.push(Object.assign({}, app, {
41 name: pack.name
42 }))
43 }
44
45 // set default timeout
46 let timeout = (app.env.NODE_ENV === 'development') ? 0 : 30e3
47
48 if (command.opt.timeout) {
49 if (isNaN(+command.opt.timeout)) {
50 timeout = null
51 } else {
52 timeout = +command.opt.timeout
53 }
54 }
55
56 // remember old workers
57 const workers = Worker.workerList.filter(worker => worker.name === command.app)
58
59 startWorkers(config, app.dir, pack, app.args, app.env).then(data => {
60 // kill old workers
61 const killed = workers.map(worker => {
62 if (worker.kill(command.opt.signal, timeout)) {
63 return worker.once('exit')
64 }
65 })
66
67 return Promise.all(killed).then(() => {
68 if (nameChanged) {
69 // remove old version
70 const oldIndex = config.apps.findIndex(app => app.name === command.app)
71 config.apps.splice(oldIndex, 1)
72 }
73
74 data.killed = killed.length
75 resolve(data)
76 })
77 }).catch(reject)
78 })
79}