-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (36 loc) · 1.1 KB
/
index.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
const express = require('express');
const morgan = require('morgan');
const connect = require('./config/db');
const createHttpError = require('http-errors');
const cors = require('cors');
const { swaggerUi, specs } = require('./swagger');
require('dotenv').config();
const routes = require('./routes');
const app = express();
const artificialDelay = (req, res, next) => {
setTimeout(next, 1000);
};
const port = process.env.PORT || 4000;
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(morgan('combined'));
app.use(express.json());
app.use(artificialDelay);
app.use(routes);
app.use((req, res, next) => {
next(createHttpError(404, 'Endpoint not found'));
});
app.use((error, req, res, next) => {
console.error(error);
let errorMessage = 'An unknown error occurred';
let statusCode = 500;
if (createHttpError.isHttpError(error)) {
statusCode = error.status;
errorMessage = error.message;
}
res.status(statusCode).json({ error: errorMessage });
});
app.listen(port, async () => {
await connect();
});