-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
73 lines (58 loc) · 1.59 KB
/
app.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
const path = require('path');
const express = require('express');
const app = express();
const log = require('./utils/log');
global.config = require('./config.js');
const publicDir = path.join(config.appRoot, 'public');
const viewsDir = path.join(config.appRoot, 'views');
app.set('view engine', 'pug');
app.use(express.static(publicDir));
app.use(express.json());
app.use(recordConnection);
let server;
const dbRouter = require('./routes/db.js').router;
app.get('/', renderHomepage);
app.use('/api', dbRouter);
app.all('*', catchPageNotFound);
app.use(handleError);
function recordConnection(req, res, next) {
let connectingIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
log.debug(`${req.method} from ${connectingIp} for ${req.url}.`);
next();
}
function renderHomepage(req, res) {
let options = {
title: 'APP',
message: 'Hello world!'
};
res.render(path.join(viewsDir, 'index'), options);
}
function catchPageNotFound(req, res, next) {
log.debug(`${req.url} not found.`);
res.status(404).send('Error');
}
function handleError(error, req, res, next) {
if (res.headersSent) {
next(error);
return;
}
log.error(error);
res.status(500).send(error.message);
}
function start() {
server = app.listen(config.listenPort, () => {
log.info(`Server listening on ${config.listenAddress}.`);
});
}
function close() {
log.info('Closing server...');
server.close();
}
const exportList = {
start,
close,
};
if (process.env.NODE_ENV === 'test') {
exportList.app = app;
}
module.exports = exportList;