-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
85 lines (66 loc) · 2.54 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
const path = require('path');
require('colors')
const express = require('express')
const dotenv = require('dotenv');
const morgan = require('morgan');
// eslint-disable-next-line import/no-extraneous-dependencies
const xss = require('xss-clean')
// eslint-disable-next-line import/no-extraneous-dependencies
const mongoSanitize = require('express-mongo-sanitize');
// eslint-disable-next-line import/no-extraneous-dependencies
const cors = require('cors');
// eslint-disable-next-line import/no-extraneous-dependencies
const compression = require('compression')
// eslint-disable-next-line import/no-extraneous-dependencies
const rateLimit = require('express-rate-limit')
// eslint-disable-next-line import/no-extraneous-dependencies
const hpp = require('hpp');
const { webhookCheckout } = require('./services/order')
dotenv.config({ path: ".env" })
//- connect to DB
const dbConnection = require('./config/database')
dbConnection()
//- express app
const app = express();
if (process.env.NODE_ENV === 'development') app.use(morgan('dev'))
app.use(express.static(path.join(__dirname, 'uploads')))
// allowing other domains to serve routes
app.use(cors())
app.options('*', cors())
// compress all responses
app.use(compression())
// checkout webhook
app.post('/webhook-checkout', express.raw({ type: 'application/json' }), webhookCheckout)
// to apply data santization
app.use(express.json({ limit: "20kb" }))
app.use(mongoSanitize());
app.use(xss())
const limiter = 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',
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
})
// Apply the rate limiting middleware to all requests
app.use('/api', limiter)
app.use(hpp({ whitelist: ['price', 'sold', 'quantity', 'ratings'] }));
// initaite routes
const initRoutes = require('./routes/index')
initRoutes(app)
//- Middlewares
const errorMiddleware = require('./middleware/errorMiddleware')
errorMiddleware(app)
// initalize server
const { PORT } = process.env
const server = app.listen(PORT, () => {
console.log(`Server running ✅✅`.grey, `http://localhost:${PORT}`.underline.blue)
})
// handel rejection outside express
process.on('unhandledRejection', (error) => {
server.close(() => {
console.error(`unhandledRejection error: ${error.name} | ${error.message}`)
process.exit(1)
})
})