This repository has been archived by the owner on Apr 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
startUp.js
186 lines (159 loc) · 6.73 KB
/
startUp.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
(function () {
"use strict";
var express = require('express');
var bodyParser = require('body-parser');
var swig = require('swig');
var uuid = require('node-uuid');
var cors = require('cors');
var mongoose = require('mongoose');
var config = require(__base + 'cfg/config');
function getDbString(config) { //Create the DB connection string
var dbConnection = "mongodb://";
if (config.username.length > 0 && config.password.length > 0) {
dbConnection += config.username + ":" + config.password + "@";
}
return dbConnection + config.uri + ":" + config.port + "/" + config.collection;
}
function setupDb() {
//Create the connection to mongodb
console.log("Going to connect to " + getDbString(config.database));
mongoose.connect(getDbString(config.database));
var db = mongoose.connection;
// DB CONNECTION EVENTS:
db.on('connected', function () { //When successfully connected
console.log('Mongoose connected');
});
db.on('error', function (err) {// If the connection throws an error
console.log('Mongoose default connection error: ' + err);
});
db.on('disconnected', function () { // When the connection is disconnected
console.log('Mongoose default connection disconnected');
});
db.on('open', function () {
console.log("Mongoose connection open");
});
}
function setupToken() {
//Setup access token
if (config.server.accessToken) {
global.accessToken = config.server.accessToken;
} else {
global.accessToken = uuid.v4(); //Generate a default token when none is set
}
console.log('Your requests must contain the following token: ' + accessToken);
}
module.exports = {
start: function (done) {
// Parallelize
const numCPUs = require('os').cpus().length;
const cluster = require('cluster');
const consoleStamp = require('console-stamp');
if (cluster.isMaster) {
// Setup timestamps for logging
consoleStamp(console, {
metadata: function () {
return ("[MASTER]");
},
colors: {
stamp: "yellow",
label: "white",
metadata: "red"
}
});
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
var worker = cluster.fork();
console.log("Spwaning worker " + worker.id);
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
// Setup timestamps for logging
consoleStamp(console, {
metadata: function () {
return ("[Worker " + cluster.worker.id + "]");
},
colors: {
stamp: "yellow",
label: "white",
metadata: "green"
}
});
setupDb();
//Setup the token only once so all worker share the same secret
setupToken();
//Setup application
var app = express();
// Add parser to get the data from a POST
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//Set swig as template engine for our main page
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __appbase + '/views');
app.set('view cache', false);
//Set up our router
var router = express.Router();
// this happens for every request
router.use(function (req, res, next) {
console.log('Request incoming: ' + req.url);
//Allow all GET requests as these do not modify data and we want users to be able to see that basic stuff
if (req.method === 'GET') {
return next();
}
//Otherwise check if we got a token
var sentToken = req.query.token;
if (!sentToken) {
console.log('401 - no token sent');
return res.status(401).send({ //Send a nice little message to remind the user that he needs to supply a token
message: 'Need to send a token',
code: 401
});
}
//Also check if the token is valid or not
if (sentToken == accessToken) {
return next();
} else {
console.log('401 - wrong token sent');
return res.sendStatus(401);
}
});
//Add cors support for all routes
app.use(cors({
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false
}));
//Include routes from external file
require(__base + 'routes')(app, router);
// prefix for all routes
app.use('/api', router);
//Route for doc folder
app.use('/doc', express.static('apidoc'));
//Character images
app.use('/misc/images/', express.static('misc/images'));
// Service the favicon
app.get('/favicon.ico', function(req, res){
res.sendFile(__base + 'apidoc/img/favicon.ico');
});
//Redirect to docs
app.get('*', function (req, res) {
res.redirect('/doc/');
});
//Start listening for requests
var port = config.server.port || 8080; //set a default port if the config file does not contain it
app.listen(port);
console.log('is listening on port ' + port);
}
},
stop: function (done) {
if (!context || !context.server) {
console.log('Server stopped');
return;
}
context.server.close(done);
}
};
}());