UNPKG

2.08 kBJavaScriptView Raw
1
2'use strict';
3
4module.exports = function (config) {
5 var connect = require('connect');
6 var bodyParser = require('body-parser');
7 var cookieParser = require('cookie-parser');
8 var serveStatic = require('serve-static');
9 var query = require('qs-middleware');
10 var app = connect();
11
12 var benchmark = require('./benchmark')(config);
13 var renderer = require('./renderer')(config);
14 var processor = require('./processor')(config, renderer);
15
16 renderer.initDustExtensions();
17 if (!config.argv['compile-on-demand']) {
18 renderer.compileTemplates();
19 }
20
21 if (config.env.isDevelopment()) {
22 renderer.watchTemplates();
23 renderer.watchDustExtensions();
24 }
25
26 app.use(benchmark);
27 app.use(query({
28 allowDots: false
29 }));
30 app.use(cookieParser());
31 app.use(config.web.tests, serveStatic(config.path.tests));
32
33 if (config.env.isProduction()) {
34 app.use(config.web.public, serveStatic(config.path.public, {
35 maxAge: 1000 * 60 * 60 * 24 * 365
36 }));
37 } else {
38 app.use(config.web.resources, renderer.assetServer());
39 }
40
41 config.middleware.forEach(function (args) {
42 app.use.apply(app, args);
43 });
44
45 app.use('/ping', processor.ping);
46 app.use('/template', bodyParser.json({limit: config.argv['max-post-size']}));
47 app.use('/template', processor.api);
48
49 app.use(processor.timestamp);
50 app.use(processor.shunterVersion);
51 app.use(processor.intercept);
52 app.use(processor.proxy);
53
54 app.listen(config.argv.port, function () {
55 config.log.debug('Worker process ' + process.pid + ' started in ' + config.env.name + ' mode, listening on port ' + config.argv.port);
56 });
57 process.on('uncaughtException', function (err) {
58 if (err.code === 'EADDRINUSE') {
59 config.log.error('Worker process ' + process.pid + ' died, something is already listening on port ' + config.argv.port);
60 // Exit with status 0, so server doesn't attempt to respawn
61 process.exit(0);
62 } else {
63 config.log.error(err);
64 process.exit(1);
65 }
66 });
67
68 process.on('message', function (msg) {
69 if (msg === 'force exit') {
70 process.exit(0);
71 }
72 });
73 process.on('disconnect', function () {
74 process.exit(0);
75 });
76};