-
Notifications
You must be signed in to change notification settings - Fork 44
/
server.js
94 lines (77 loc) · 2.27 KB
/
server.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
91
92
93
94
const path = require('path');
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const cors = require('cors');
const compression = require('compression');
const rateLimit = require('express-rate-limit');
const hpp = require('hpp');
dotenv.config({ path: 'config.env' });
const ApiError = require('./utils/apiError');
const globalError = require('./middlewares/errorMiddleware');
const dbConnection = require('./config/database');
// Routes
const mountRoutes = require('./routes');
const { webhookCheckout } = require('./services/orderService');
// Connect with db
dbConnection();
// express app
const app = express();
// Enable other domains to access your application
app.use(cors());
app.options('*', cors());
// compress all responses
app.use(compression());
// Checkout webhook
app.post(
'/webhook-checkout',
express.raw({ type: 'application/json' }),
webhookCheckout
);
// Middlewares
app.use(express.json({ limit: '20kb' }));
app.use(express.static(path.join(__dirname, 'uploads')));
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
console.log(`mode: ${process.env.NODE_ENV}`);
}
// Limit each IP to 100 requests per `window` (here, per 15 minutes)
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
message:
'Too many accounts created from this IP, please try again after an hour',
});
// Apply the rate limiting middleware to all requests
app.use('/api', limiter);
// Middleware to protect against HTTP Parameter Pollution attacks
app.use(
hpp({
whitelist: [
'price',
'sold',
'quantity',
'ratingsAverage',
'ratingsQuantity',
],
})
);
// Mount Routes
mountRoutes(app);
app.all('*', (req, res, next) => {
next(new ApiError(`Can't find this route: ${req.originalUrl}`, 400));
});
// Global error handling middleware for express
app.use(globalError);
const PORT = process.env.PORT || 8000;
const server = app.listen(PORT, () => {
console.log(`App running running on port ${PORT}`);
});
// Handle rejection outside express
process.on('unhandledRejection', (err) => {
console.error(`UnhandledRejection Errors: ${err.name} | ${err.message}`);
server.close(() => {
console.error(`Shutting down....`);
process.exit(1);
});
});