-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
189 lines (146 loc) · 5.35 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const path = require('path');
const express = require('express');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');
const hpp = require('hpp');
const morgan = require('morgan');
const cors = require('cors');
const cookieparser = require('cookie-parser');
const compression = require('compression');
const AppError = require('./utils/AppError');
const globalErrorhandler = require('./Controllers/errorController');
const tourRouter = require('./Routes/tourRoute');
const userRouter = require('./Routes/userRoute');
const reviewRouter = require('./Routes/reviewRoute');
const bookingRouter = require('./Routes/bookingRoutes');
const viewRouter = require('./Routes/viewRoutes');
const app = express();
app.use(
cors({
origin: 'http://127.0.0.1:3000',
credentials: true,
})
);
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views')); //this is the ideal way for finding the path instead of ./
//serving static file
app.use(express.static(path.join(__dirname, 'public'))); //this is used to get link css etc
//this middleware servers the static files in the folder
/////////Middleware///////////
//Security HTTP headers
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'", 'https:', 'http:', 'data:', 'ws:'],
baseUri: ["'self'"],
fontSrc: ["'self'", 'https:', 'http:', 'data:'],
scriptSrc: ["'self'", 'https:', 'http:', 'blob:'],
styleSrc: ["'self'", "'unsafe-inline'", 'https:', 'http:'],
},
})
);
//Development logging
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
} //this is 3rd party middleware
//morgan is used as similar to req,res,next
//limit request from the same IP
const limiter = rateLimit({
max: 500, //no of request
windowMs: 60 * 60 * 1000, //allows 100 request for same Ip in 1 hour(converted into ms)
message: 'Too many request from this Ip.Please try again in an hour!',
});
app.use('/', limiter);
//Body Parser, reading data from body into req.body
app.use(express.json()); //this is called middleware
//middleware is the function that can modilfy the iocoming request
app.use(express.urlencoded()); //the way form for updating user to the user is also called urlencoded
//we need this middleware to parse the update user form data into the server
app.use(cookieparser()); //parses the cookie after login
//Data sanitization against NOSQL query injection
app.use(mongoSanitize()); //it removes all of the $ sign
// Data Sanitization against XSS
app.use(xss()); //prevents attack in the form of malacious html code
//Prevent parameter pollution
app.use(
hpp({
whitelist: [
'duration',
'ratingsQuantity',
'ratingsAverage',
'maxGroupSize',
'difficulty',
'price',
], //it means duplicate of duration is allowed
})
);
// app.use((req, res, next) => {
// console.log('Hello from the middleware'); //never forget to write next otherwise it will be stuck and never give response
// next();
// });
app.use(compression()); //compresses json text for the client
//Test middleware
app.use((req, res, next) => {
req.requestTime = new Date().toISOString(); //req.requestTime is defining a property in request
//toISOstring changes into string
// console.log(req.cookies);
next();
});
////////////Route Handler////////////////
// app.get('/', (req, res) => {
// res.status(200).json({
// name: 'Swejal Shrestha',
// age: 22,
// });
// });
// app.post('/', (req, res) => {
// res.send('You can point this');
// });
// const tour = fs.readFileSync(`${__dirname}/dev-data/data/tours-simple.json`);
// const tours = JSON.parse(tour);
// console.log(tours);
/////////////or//////////
//////////////////Routes///////////////
//app.get('/api/v1/tours', getAllTours);
//app.get('/api/v1/tours/:id', getSelectedTour);
//app.post('/api/v1/tours', createTour);
//app.patch('/api/v1/tours/:id', updateSelectedTour);
//app.delete('/api/v1/tours/:id', deleteSelectedTour);
///////////you can do this OR///////////
// app.route('/api/v1/tours').get(getAllTours).post(createTour);
// app
// .route('/api/v1/tours/:id')
// .get(getSelectedTour)
// .patch(updateSelectedTour)
// .delete(deleteSelectedTour);
// app.route('/api/v1/users').get(getAllUsers).post(createUser);
// app
// .route('/api/v1/users/:id')
// .get(getSelectedUser)
// .patch(updateSelectedUser)
// .delete(deleteSelectedUser);
app.use('/', viewRouter);
app.use('/api/v1/tours', tourRouter);
app.use('/api/v1/users', userRouter);
app.use('/api/v1/reviews', reviewRouter);
app.use('/api/v1/bookings', bookingRouter);
//this process is called mounting
app.all('*', (req, res, next) => {
// res.status(404).json({
// status: 'failed',
// message: `Cant connect to ${req.originalUrl}.Try again`,
// });
// next();
// const err = new Error(`Cant connect to ${req.originalUrl}.Try again`);
// err.statusCode = 404;
// err.status = 'Fail';
// next(err); //if there is any variable passing through next then
// //express will automatically thinl of it as a error and passes to the error handling middleware
next(new AppError(`Cant connect to ${req.originalUrl}.Try again`, 404));
});
//////Error Handler Middleware
app.use(globalErrorhandler);
//////////////////Start Server////////////////
module.exports = app;