-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
90 lines (74 loc) · 2.3 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
/* eslint-disable no-console */
import dotenv from 'dotenv';
import express from 'express';
import compression from 'compression';
import { createHttpTerminator } from 'http-terminator';
import helmet from 'helmet';
import createError from 'http-errors';
import cors from 'cors';
import router from './src/routes/main.router.js';
import config from './src/config/config.js';
// defining the port to run the server
const PORT = process.env.PORT || 8000;
const ENV = process.env.NODE_ENV;
// Load environment variables from .env file
dotenv.config({
path: ENV ? `./.env.${ENV}` : './.env',
});
// Create Express server
const app = express();
// Helmet helps you secure your Express apps by setting various HTTP headers
app.use(helmet());
// middleware
app.use(compression());
// x-powered-by header banner
app.disable('x-powered-by');
// cors configuration
app.use(
cors({
origin: (origin, callback) => {
if (config.cors_whitelist.includes(origin)) {
callback(null, true);
} else {
callback(new createError(403, 'Not allowed by CORS'));
}
},
optionsSuccessStatus: 200,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
}),
);
// routing middleware in express
app.use(router);
// running express application on the port defined in env or 8000
const server = app.listen(PORT, () => {
console.log(`App is running at http://localhost:${PORT} in ${ENV} mode`);
console.log('Press CTRL-C to stop');
});
// 404 handler
app.use((req, res, next) => {
next(new createError.NotFound());
});
// Error handler
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
const status = err.status || 500;
res.status(status).json({
success: false,
message: err.message || 'Internal Server Error',
status_code: status,
data: {},
});
});
// Graceful shutdown
// implements logic for gracefully terminating an express.js server.
const httpTerminator = createHttpTerminator({ server });
process.on('SIGTERM', async () => {
console.log('SIGTERM signal received: closing HTTP server');
await httpTerminator.terminate();
});
process.on('SIGINT', async () => {
console.log('SIGINT signal received: closing HTTP server');
await httpTerminator.terminate();
});