This repository has been archived by the owner on Aug 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
99 lines (78 loc) · 2.67 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
97
98
99
(function() {
'use strict';
/**
* Author: Christian Schulze
* License: MIT
* Date: 2016/05/10
*
* Main entry point for the Pythia app, providing the api as well as the frontend.
*/
var express = require('express'),
app = exports.app = express(),
http = require('http').Server(app),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
io = require('socket.io')(http),
path = require('path'),
config = require('./config.js');
/* Middleware */
var api = require('./api')(io),
frontend = require('./frontend')(io);
/* POST body parsing */
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
/* set up CORS header */
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
/* Custom middleware */
app.use(api);
app.use(frontend);
/* Mongoose */
var mongooseIsConnected = false;
/* Establish database connection: either use the specified `DB_URI=ADDRESS_TO_MONGODB`
via the environment, or fall back to the default path */
var connectionFn = function() {
var database = process.env.MONGODB_URI || 'localhost:27017/pythia';
mongoose.connect(database);
};
// connect
connectionFn();
mongoose.connection.on('connected', function() {
console.log('Mongoose connected to database');
mongooseIsConnected = true;
});
mongoose.connection.on('error', function(err) {
console.error(err);
// closing via driver
mongoose.connection.db.close();
// retry connection until succeeding
connectionFn();
});
mongoose.connection.on('disconnected', function() {
console.log('Mongoose disconnected');
mongooseIsConnected = false;
});
var handleDisconnect = function() {
console.log('attempting graceful shutdown.');
if (mongooseIsConnected) {
mongoose.connection.close(function() {
console.log('Mongoose is disconnecting due to app termination');
process.exit(0);
});
} else {
process.exit(0);
}
};
/* Mongoose disconnection on app termination */
process.on('SIGINT', handleDisconnect);
process.on('SIGTERM', handleDisconnect);
app.set('port', (process.env.PORT || 5667));
http.listen(app.get('port'), function() {
console.log('listening on http://localhost:' + app.get('port'));
});
})();