-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
70 lines (62 loc) · 2.05 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');
const morgan = require('morgan');
const compression = require('compression');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const DB_CONNECTION = require('./constants/DB_CONNECTION');
const apiDocumentation = YAML.load('./swagger.yml');
const swaggerDocs = require('./swagger');
const { startMetrics, restApiHistogram } = require('./utils/serverMetrics');
const responseTime = require('response-time');
const cors = require('cors');
const app = express();
const run = async () => {
try {
await mongoose.connect(DB_CONNECTION, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('DB connected successfully');
/*Middlewares */
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ etended: false }));
app.use(
responseTime((req, res, time) => {
if (req?.route?.path) {
restApiHistogram.observe(
{
method: req.method,
route: req.route.path,
status_code: res.statusCode,
},
time * 1000
);
}
})
);
// Application middlewares
app.use(cors({ origin: '*' }));
app.use(morgan('dev'));
app.use(compression());
app.use('/api', routes);
app.use(
'/api-docs',
swaggerUi.serve,
swaggerUi.setup(apiDocumentation)
);
//
app.listen(process.env.PORT, () => {
console.log('Server has started!');
startMetrics();
swaggerDocs(app, process.env.PORT);
});
} catch (err) {
console.log(err.message);
process.exit(1);
}
};
run().catch((err) => console.log(err.message));
module.exports = app;