-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathserver.js
73 lines (58 loc) · 1.68 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
67
68
69
70
71
72
73
import httpContext from 'express-http-context';
import express from 'express';
import bodyParser from 'body-parser';
var app = express();
var port = process.env.PORT || '80';
var hostname = process.env.HOST || '0.0.0.0';
var bodySizeLimit = process.env.MAX_BODY_SIZE || '100kb';
// parse JSONAPI content type
app.use(bodyParser.json({
type: function(req) { return /^application\/vnd\.api\+json/.test(req.get('content-type')); },
limit: bodySizeLimit
}));
app.use(bodyParser.urlencoded({ extended: false }));
// set JSONAPI content type
app.use('/', function(req, res, next) {
res.type('application/vnd.api+json');
next();
});
app.use(httpContext.middleware);
app.use(function(req, res, next) {
httpContext.set('request', req);
httpContext.set('response', res);
next();
});
const errorHandler = function(err, req, res, next) {
res.status(err.status || 400);
res.json({
errors: [ {title: err.message} ]
});
};
// start server
const server = app.listen( port, hostname, function() {
console.log(`Starting server on ${hostname}:${port} in ${app.get('env')} mode`);
});
// faster stopping
let exitHandler = function(server) {
console.debug("Preparing to shut down");
server.close( () => {
console.debug("Shut down complete");
});
};
/**
* Sets a new handler for shutting down the server.
*
* @arg functor Function taking one argument (the result of app.listen
* when starting the server) which should gracefully stop the server.
*/
function setExitHandler( functor ) {
this.exitHandler = functor;
}
process.on('SIGTERM', () => exitHandler(server) );
process.on('SIGINT', () => exitHandler(server) );
export default app;
export {
app,
errorHandler,
setExitHandler
}