-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
90 lines (70 loc) · 1.98 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const express = require('express');
const morgan = require('morgan');
const HttpError = require('./models/httperror');
const mongoose = require('mongoose');
const config = require('./configurator').config();
const app = express();
let httpServer;
let dbClient;
async function init() {
console.log('Connecting DB...');
dbClient = await mongoose.connect(config.dburl, {
useNewUrlParser: true,
useUnifiedTopology: true
});
app.locals.config = config;
console.log('Loading Modules...');
// logger
app.use(morgan({
format: 'short',
stream: {
write: (str) => {
console.log(str);
}
}
}));
// routes
app.use('/auth', require('./routes/auth'));
app.use('/profile', require('./routes/profile'));
app.use('/hear', require('./routes/hear'));
app.use('/test', require('./routes/test'));
// error handler
app.use((err, req, res, next) => {
let status = 500;
let message = '';
if (err instanceof HttpError) {
status = err.status;
message = err.message;
}
else if (err instanceof Error) {
message = `${err.name}: ${err.message}`;
}
if (!message || config.product)
message = 'internal server error';
console.log(err);
res.status(status)
.send({
result: false,
status: status,
message: message
});
});
httpServer = app.listen(config.port, config.host, () => console.log(`Listening on port ${config.port}...`));
// send ready signal to PM2 (Process Manager)
try {
process.send('ready');
} catch (e) {
console.log(e);
}
}
async function stopServer() {
console.log('Stopping server');
dbClient.close();
httpServer.close();
console.log('Stopped');
}
// process exit signal
process.on('SIGINT', function () {
stopServer();
});
init();