-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
84 lines (68 loc) · 2.23 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
const path = require('path');
const express = require('express');
const dotenv = require('dotenv');
const cors = require("cors");
const compression = require("compression");
dotenv.config({ path: 'config.env' });
const rateLimit = require("express-rate-limit");
const hpp = require('hpp');
const mongoSanitize = require("express-mongo-sanitize");
const xss = require("xss-clean");
const dbConnection = require('./config/database');
const ApiError = require("./utils/apiError");
const errorMiddleware = require('./middlewares/errorMiddleware');
require('mongoose').set('strictQuery', false);
const { webhookCheckout } = require('./services/orderService');
const app = express();
dbConnection();
app.use(express.json({ limit: '20kb' }));
app.use(mongoSanitize());
//enable others domans to access your api
app.use(cors());
app.options("*", cors());
//compress all responses
app.use(compression());
app.use(xss());
//Check Webhoob
app.post(
"/webhook-checkout",
webhookCheckout
);
app.use(express.static(path.join(__dirname, 'uploads')));
console.log("mode : ", process.env.NODE_ENV);
//routes
const mountRoute = require('./routes');
const { log } = require('console');
mountRoute(app);
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
message:
"Too many accounts created from this IP, please try again after an hour",
});
// Apply the rate limiting middleware to API calls only
app.use("/api", apiLimiter);
app.use(
hpp({
whitelist: ["ratingsAverage", "ratingsQuantity", "quantity", 'sold', 'price'],
})
); // <- THIS IS THE NEW LINE
//404 error if not found page
app.all('*', (req,res,next) => {
next(new ApiError("can't find this page",404));
});
//Global error middleware
app.use(errorMiddleware);
//Running Server
const port=process.env.PORT || 3000
const server = app.listen(port, () => {
console.log(`Server Running on port ${port} ...`);
});
//handle rejection errors outside express
process.on('unhandledRejection', (err) => {
console.error(`unhandledRejection : ${ err.name } | ${ err.message}`);
server.close(() => {
console.error("shutting down ... ");
process.exit(1);
});
});