-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
106 lines (91 loc) · 3.21 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
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
const express = require('express'),
exphbs = require('express-handlebars'),
hbsHelpers = require('handlebars-helpers'),
hbsLayouts = require('handlebars-layouts'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
errorhandler = require('errorhandler'),
csrf = require('csurf'),
morgan = require('morgan'),
favicon = require('serve-favicon'),
router = require('./routes/router'),
database = require('./lib/database'),
seeder = require('./lib/dbSeeder'),
app = express(),
port = 3000;
class Server {
constructor() {
this.initViewEngine();
this.initExpressMiddleWare();
this.initCustomMiddleware();
this.initDbSeeder();
this.initRoutes();
this.start();
}
start() {
app.listen(port, (err) => {
console.log('[%s] Listening on http://localhost:%d', process.env.NODE_ENV, port);
});
}
initViewEngine() {
const hbs = exphbs.create({
extname: '.hbs',
defaultLayout: 'master'
});
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
hbsLayouts.register(hbs.handlebars, {});
}
initExpressMiddleWare() {
app.use(favicon(__dirname + '/public/assets/images/favicon.ico'));
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(errorhandler());
app.use(cookieParser());
app.use(csrf({ cookie: true }));
app.use((req, res, next) => {
let csrfToken = req.csrfToken();
res.locals._csrf = csrfToken;
res.cookie('XSRF-TOKEN', csrfToken);
next();
});
process.on('uncaughtException', (err) => {
if (err) console.log(err, err.stack);
});
}
initCustomMiddleware() {
if (process.platform === "win32") {
require("readline").createInterface({
input: process.stdin,
output: process.stdout
}).on("SIGINT", () => {
console.log('SIGINT: Closing MongoDB connection');
database.close();
});
}
process.on('SIGINT', () => {
console.log('SIGINT: Closing MongoDB connection');
database.close();
});
}
initDbSeeder() {
database.open(() => {
//Set NODE_ENV to 'development' and uncomment the following if to only run
//the seeder when in dev mode
//if (process.env.NODE_ENV === 'development') {
// seeder.init();
//}
seeder.init();
});
}
initRoutes() {
router.load(app, './controllers');
// redirect all others to the index (HTML5 history)
app.all('/*', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
}
}
let server = new Server();