-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
96 lines (85 loc) · 2.47 KB
/
index.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const cluster = require('cluster');
const express = require('express');
const morgan = require('morgan');
const uuid = require('uuid');
const bodyParser = require('body-parser');
const app = require('./app');
const log = app.logger;
const server = express();
// enable CORS in development
if (app.config.isDevelopment) {
server.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization',
);
res.header(
'Access-Control-Allow-Methods',
'GET, PUT, POST, PATCH, DELETE, OPTIONS',
);
if (req.method.toLowerCase() === 'options') res.status(200).end();
else next();
});
}
// Assign a unique ID to each request
server.use((req, res, next) => {
req.id = uuid.v4().split('-').pop();
res.set('X-Flow-Id', req.id);
next();
});
// Enable logging for debugging and tracing purposes
server.use(
morgan(
':date[web] [IP :req[X-Forwarded-For]] [Flow :res[X-Flow-Id]] :method :url :status :response-time[3]ms',
),
);
// Parse urlencoded and json POST data
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());
// Route the API
server.use('/app/api', app.api.router);
// Register error middleware
server.use(app.db.errorHandler);
server.use(app.error.errorHandler);
server.use(app.error.notFoundHandler);
// perform DB initialization once
const setup = app.db.setup(true, app.config.isDevelopment);
if (require.main == module) {
// Create workers
if (cluster.isMaster) {
log.debug('Creating %d cluster workers...', app.config.numCPUs);
for (let i = 0; i < app.config.numCPUs; i++) cluster.fork();
cluster.on('exit', (worker, code, signal) => {
log.info(
'Worker PID %s died (%s). Restarting...',
worker.process.pid,
signal,
);
console.log("FORKING");
cluster.fork();
});
}
if (!cluster.isMaster) {
// Start the server on each worker
server.listen(app.config.port, app.config.host, async () => {
log.info(
'Started server %s on port %d, PID: %d',
app.config.host,
app.config.port,
process.pid,
);
});
}
}
else {
let HTTPserver = server.listen(app.config.port, app.config.host, () => {
log.info(
'Started TEST server %s on port %d, PID: %d',
app.config.host,
app.config.port,
process.pid,
);
});
module.exports = { server: HTTPserver, setup };
}