-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
68 lines (57 loc) · 1.6 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
import express from 'express';
import cors from 'cors';
import env from '#utils/env.js';
import { closeConnection } from '#utils/db.js';
import { __dirname } from '#utils/file.js';
import path from 'path';
import { errorLogger, requestLogger } from '#middlewares/loggers.js';
import api from '#routes/api.js';
import handlebars from '#utils/handlebars.js';
const app = express();
app.use(express.json());
app.use(cors());
app.set('view engine', 'hbs');
handlebars();
// don't record logs if testing
/* c8 ignore start */
if (env.NODE_ENV !== 'test') {
app.use(requestLogger);
}
/* c8 ignore end */
app.use('/api', api);
app.use(express.static('public'));
app.get('/docs/*', (req, res) => {
res.sendFile(path.join(__dirname, 'public/docs/index.html'));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
// don't record logs if testing
/* c8 ignore start */
if (env.NODE_ENV !== 'test') {
app.use(errorLogger);
}
// error handler
app.use((err, req, res) => {
if (env.NODE_ENV === 'dev' || env.NODE_ENV === 'test') {
res
.status(err?.status || 500)
.json({ message: err?.message, name: err?.name, stack: err?.stack });
} else {
res
.status(err?.status || 500)
.json({ message: err?.message, name: err?.name });
}
});
/* c8 ignore end */
const port = env.PORT || 3000;
const server = app.listen(port, () => {
console.log(`API listening on port ${port}`);
});
process.on('SIGINT', () => {
server.close(() => {
closeConnection();
console.log('MongoDB connection and server closed');
});
});
export default app; // For testing