-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
95 lines (74 loc) · 2.19 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
95
const express = require('express');
const dotenv = require('dotenv');
const colors = require('colors');
const path = require('path');
const morgan = require('morgan');
const hpp = require('hpp');
const cors = require('cors');
const helmet = require('helmet');
const xss = require('xss-clean');
const rateLimit = require('express-rate-limit');
const mongoSanitize = require('express-mongo-sanitize');
const cookieParse = require('cookie-parser');
const fileUpload = require('express-fileupload');
const errorHandler = require('./middleware/errorHandler');
const connectDB = require('./config/db');
// Load env file
dotenv.config({ path: './config/config.env' });
// Bring in routers files
const bootcamps = require('./routes/bootcamps');
const courses = require('./routes/courses');
const auth = require('./routes/auth');
const users = require('./routes/users');
const reviews = require('./routes/reviews');
// Connect to database
connectDB();
const app = express();
// Body Parser
app.use(express.json());
// Cookie Parser
app.use(cookieParse());
// Dev Logger using morgan
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// File upload Middleware
app.use(fileUpload());
// Protect Middleware
app.use(helmet());
// Sanitize mongo queries
app.use(mongoSanitize());
// Enable CORS
app.use(cors());
// Protect against http param pollution
app.use(hpp());
// Protect from XSS
app.use(xss());
// Rate Limiting
const limiter = rateLimit({
windowMs: 10 * 60 * 1000,
max: 100
});
app.use(limiter);
// Set Public Folder
app.use(express.static(path.join(__dirname, 'public')));
// Mount Router
app.use('/api/v1/bootcamps', bootcamps);
app.use('/api/v1/courses', courses);
app.use('/api/v1/auth', auth);
app.use('/api/v1/users', users);
app.use('/api/v1/reviews', reviews);
// Mount error handler middleware
app.use(errorHandler);
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () =>
console.log(
`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
)
);
// For Unhandeled Rejection of promise
process.on('unhandledRejection', (err, promise) => {
// @ts-ignore
console.log(`Error : ${err.message}`.red);
server.close(() => process.exit(1));
});