-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
64 lines (50 loc) · 1.53 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
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const httpStatus = require('http-status');
const passport = require('passport');
// config
const { env } = require('./config/settings');
const jwtStrategy = require('./config/passport');
// middleware
const morgan = require('./middlewares/morgan');
const { errorConverter, errorException } = require('./middlewares/errorHandler');
const authRateLimiter = require('./middlewares/authRateLimiter');
// utils
const AppError = require('./utils/AppError');
// routes
const apiRouter = require('./routes/api');
const app = express();
if (env !== 'test') {
app.use(morgan.successHandler);
app.use(morgan.errorHandler);
}
// enable cors
app.use(cors());
app.options('*', cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// jwt | passport
app.use(passport.initialize());
passport.use('jwt', jwtStrategy);
// limit repeated failed requests to auth endpoints
if (env === 'production') {
app.use('/api/v1/auth', authRateLimiter);
}
app.use('/api/v1', apiRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// // error handler
app.use((req, res, next) => {
next(new AppError(httpStatus.NOT_FOUND, 'Not found'));
});
// handle error
app.use(errorException);
// boolean needed, convert error to AppError,
app.use(errorConverter);
module.exports = app;