-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
90 lines (71 loc) · 2.3 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
const express = require('express');
const path = require('path');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');
const compression = require('compression');
const cors = require('cors');
const streamRouter = require('./routes/streamRoutes');
const songRouter = require('./routes/songRoutes');
const userRouter = require('./routes/userRoutes');
const tokenRouter = require('./routes/tokenRoutes');
const AppError = require('./utils/appError');
const globalErrorHandler = require('./controllers/errorController');
const app = express();
app.enable('trust proxy');
// Enable CORS
app.use(cors());
app.options('*', cors());
// Security HTTP Headers
app.use(helmet());
// Rate Limit Header
// Requests per ip at amount of time!
// 5000 requests from same ip in 1 hour
const limiter = rateLimit({
max: 5000,
windowMs: 60 * 60 * 1000,
message: 'Too many requests from this IP, please try again in an hour.',
});
app.use('/api', limiter);
// Body parser, reading data from body to req.body
app.use(express.json());
// Data sanitization against NoSQL query injection
// removes operators and dollar signs
app.use(mongoSanitize());
// Data sanitization against XSS
// Prevent HTML code + JS code injection! Convert them into characters!
app.use(xss());
// Serving static files
app.use(express.static(path.join(__dirname, 'assets')));
app.use(compression());
// Time adding middleware
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
next();
});
// Routers
app.use('/api/v1/streams', streamRouter);
app.use('/api/v1/songs', songRouter);
app.use('/api/v1/users', userRouter);
app.use('/api/v1/tokens', tokenRouter);
app.get('/api/v1/', (req, res) => {
res.status(200).json({
message:
'Welcome to the music streamer! Provide the endpoints (users/streams/songs)',
});
});
app.get('/', (req, res) => {
res.status(200).json({
message: 'Welcome to the music streamer! Use /api/v1 endpoints!',
});
});
// Error handlers
app.all('*', (req, res, next) => {
// const err = new Error();
// err.status = 'fail';
// err.statusCode = 404;
next(new AppError(`Can't find the ${req.originalUrl} on this server.`, 404));
});
app.use(globalErrorHandler);
module.exports = app;