forked from kriasoft/graphql-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.js
79 lines (72 loc) · 2.25 KB
/
run.js
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Node.js API Starter Kit (https://reactstarter.com/nodejs)
*
* Copyright © 2016-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
const fs = require('fs');
const path = require('path');
const cp = require('child_process');
const task = require('./task');
let build;
let server;
// Gracefull shutdown
process.once('cleanup', () => {
if (server) {
server.addListener('exit', () => {
server = null;
process.exit();
});
server.kill('SIGTERM');
} else {
process.exit();
}
});
process.on('SIGINT', () => process.emit('cleanup'));
process.on('SIGTERM', () => process.emit('cleanup'));
// Ensure that Node.js modules were installed,
// at least those required to build and launch the app
try {
build = require('./build');
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') throw err;
// Install Node.js modules with Yarn
cp.spawnSync('yarn', ['install', '--no-progress'], { stdio: 'inherit' });
// Clear Module's internal cache
try {
const Module = require('module');
const m = new Module();
// eslint-disable-next-line
m._compile(fs.readFileSync('./scripts/build.js', 'utf8'), path.resolve('./scripts/build.js'));
} catch (error) { } // eslint-disable-line
// Reload dependencies
build = require('./build');
}
module.exports = task('run', () => Promise.resolve()
// Migrate database schema to the latest version
.then(() => {
cp.spawnSync('node', ['--harmony', 'scripts/db.js', 'migrate'], { stdio: 'inherit' });
})
// Compile and launch the app in watch mode, restart it after each rebuild
.then(() => build({
watch: true,
onComplete() {
if (!server) {
// Launch `node build/server.js` on a background thread
server = cp.spawn('node',
[...(process.env.NODE_DEBUG === 'true' ? ['--inspect', '--no-lazy'] : []), 'server.js'],
{ cwd: './build', stdio: ['inherit', 'inherit', 'inherit', 'ipc'] });
} else {
server.send('reload');
}
},
}))
// Resolve the promise on exit
.then(() => new Promise((resolve) => {
process.once('exit', () => {
if (server) server.kill();
resolve();
});
})));