-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
233 lines (210 loc) · 5.2 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
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
* ## HTTP-Server for oauth2-client
*
* @module server
*/
'use strict';
const bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
chalk = require('chalk'),
dateFormat = require('dateformat'),
express = require('express'),
session = require('express-session'),
glob = require('glob'),
i18n = require('i18n'),
MemoryStore = require('memorystore')(session),
morgan = require('morgan'),
path = require('path'),
config = require('./lib/config'),
ipv4addresses = require('./lib/ipv4addresses'),
log = require('./lib/log'),
app = express(),
server = require('http').createServer(app);
let routers = { };
/**
* Weberver logging
*
* using log format starting with [time]
*/
if (config.server.verbose) {
morgan.token('time', () => {
return dateFormat(new Date(), 'HH:MM:ss');
});
app.use(morgan('[' + chalk.gray(':time') + '] ' +
':method :status :url :res[content-length] Bytes - :response-time ms'));
}
// Serve static files
app.use(express.static(config.server.docroot));
/**
* load modules
*/
glob.sync(config.server.modules + '/*/server/index.js')
.forEach((filename) => {
const regex = new RegExp(config.server.modules + '(/[^/]+)/server/index.js');
const baseRoute = filename.replace(regex, '$1');
routers[baseRoute] = require(filename);
});
// base directory for views
app.set('views', __dirname);
// render ejs files
app.set('view engine', 'ejs');
// work on post requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// work on cookies
app.use(cookieParser());
// set up i18n
i18n.configure({
defaultLocale: 'de',
directory: config.gulp.build.locales.dest,
autoReload: true,
updateFiles: false,
cookie: 'lang',
queryParameter: 'lang'
});
app.use(i18n.init);
app.use((req, res, next) => {
if (req.query.lang) {
res.cookie('lang', req.query.lang, { maxAge: 900000, httpOnly: true });
} else if (!res.cookie.lang) {
const lang = req.acceptsLanguages(...Object.keys(i18n.getCatalog()));
if (lang) {
i18n.setLocale(lang);
}
}
next();
});
// initialize req.session
app.use(session({
store: new MemoryStore({
checkPeriod: 86400000 // prune expired entries every 24h
}),
secret: 'uif fsranöaiorawrua vrw',
resave: false,
saveUninitialized: true
}));
/**
* use express in modules
*/
for (const router of Object.values(routers)) {
if (router.useExpress) {
router.useExpress(app);
}
}
// Serve static files
app.use(express.static(config.server.docroot));
/**
* Route for root dir
*
* @param {Object} req - request
* @param {Object} res - response
*/
app.get('/', (req, res) => {
res.sendFile(path.join(config.server.docroot, 'index.html'));
});
/**
* Route for app main page
*
* @param {Object} req - request
* @param {Object} res - response
*/
app.get('/app', (req, res) => {
res.render(viewPath('app'), config.getData(req));
});
/**
* Route for i18n ejs test page
*
* @param {Object} req - request
* @param {Object} res - response
*/
app.get('/i18n-ejs', (req, res) => {
res.render(viewPath('i18n-test'), config.getData(req));
});
// Fire it up!
server.listen(config.server.httpPort);
server.on('error', onError);
server.on('listening', onListening);
/**
* connect server and use routes from modules
*/
for (const [baseRoute, router] of Object.entries(routers)) {
if (router.connectServer) {
router.connectServer(server);
}
app.use(baseRoute, router.router);
}
/**
* Route for everything else
*
* @param {Object} req - request
* @param {Object} res - response
*/
app.get('*', (req, res) => {
res.status(404).render(viewPath('error'), Object.assign({
error: {
code: 404,
name: 'not found'
}
}, config.getData(req)));
});
/**
* Handle server errors
*
* @param {Object} err - error
* @param {Object} req - request
* @param {Object} res - response
* @param {Object} next - needed for complete signature
*/
app.use((err, req, res, next) => {
console.error('SERVER ERROR:', err.toString());
if (err) {
res.status(500)
.render(viewPath('error'), Object.assign({
error: {
code: 500,
name: 'server error',
error: err
}
}, config.getData(req)));
} else {
next();
}
});
/**
* Get the path for file to render
*
* @private
* @param {String} page - page type
* @param {String} type - file type (ejs, jade, pug, html)
*/
function viewPath(page = 'error', type = 'ejs') {
return config.server.modules + '/pages/views/' + page + '.' + type;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(config.server.httpPort + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(config.server.httpPort + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
log.info('server listening on ' +
chalk.greenBright('http://' + ipv4addresses.get()[0] + ':' + config.server.httpPort));
}