forked from Financial-Times/alphaville-es-interface-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
66 lines (55 loc) · 1.55 KB
/
server.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
const express = require('express');
const http = require('http');
const _ = require('lodash');
const throng = require('throng');
const bodyParser = require('body-parser');
const cors = require('cors');
const defaultConfig = require('./config');
const createServer = (config) => {
// force GC to 80% of available memory
const v8 = require('v8');
if(process.env.WEB_MEMORY) {
const gcMemory = Math.floor(parseInt(process.env.WEB_MEMORY, 10) * 4 / 5);
v8.setFlagsFromString(`--max_old_space_size=${gcMemory}`);
}
const app = express();
app.use(bodyParser.json());
app.disable('x-powered-by');
app.use(cors());
app.use(require('./router'));
require('./appSetup')(app, config);
const server = http.createServer(app);
if (config.timeout) {
server.setTimeout(config.timeout, (socket) => {
const message = `Timeout of ${config.timeout}ms exceeded`;
socket.end([
`HTTP/1.1 503 Service Unavailable`,
`Date: ${(new Date).toGMTString()}`,
`Content-Type: text/plain`,
`Content-Length: ${message.length}`,
`Connection: close`,
``,
message
].join(`\r\n`));
});
}
return server;
};
const startServer = (serverConfig) => {
const config = _.merge(defaultConfig, serverConfig);
const server = createServer(config);
server.listen(config.port, () => {
console.log('Server #%s listening on port %s', config.id, config.port);
});
return server;
};
module.exports = {
startServer
};
if (require.main === module) {
throng({
start: (id) => startServer({ id }),
workers: process.env.WEB_CONCURRENCY || 1,
lifetime: Infinity
});
}