-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
83 lines (67 loc) · 2.31 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
// built in Nodemodules
const path = require("path");
// libraries and frameworks
const express = require("express");
const app = express();
const cookieParser = require('cookie-parser')
const compression = require('compression');
const cors = require('cors');
const helmet = require("helmet");
// const httpStatus = require('http-status');
const morgan = require("morgan");
// internal modules/utils/middlewares/services
const api = require("./api");
const cookieService = require("./services/cookieService");
const jwtService = require("./services/jwtService");
const errorConverter = require('./middleware/errors/errorConverter');
const errorHandler = require('./middleware/errors/errorHandler');
// parsing cookies for auth
app.use(cookieParser())
// adding userId to the request object if exists w/o verifying the token
app.use((req, res, next) => {
const { __session } = req.cookies;
req.userId = "Guest";
if (__session) {
// decode jwt token from cookie session and verify
const token = cookieService.decrypt(__session);
const payload = jwtService.decode(token);
if (payload) {
req.userId = payload.id;
}
};
next();
});
// setting up logger
if (process.env.NODE_ENV === "development") {
app.use(morgan("dev"));
};
// opening cors for development
app.use(cors());
// setting security HTTP headers
app.use(helmet({
crossOriginResourcePolicy: false,
}));
// parsing incoming requests with JSON body payloads
app.use(express.json());
// parsing incoming requests with urlencoded body payloads
app.use(express.urlencoded({ extended: true }));
// handling gzip compression
app.use(compression());
// redirecting incoming requests to api.js
app.use(`/api`, api);
// setting up a 404 error handler
app.all("*", (req, res, next) => {
res.status(404).end();
});
// converting error to AppError, if needed
app.use(errorConverter);
// handling error
app.use(errorHandler);
// returning the main index.html, so react-router render the route in the client
// app.get("*", (req, res) => {
// res.sendFile(path.resolve(__dirname, "../", "client/", "build", "index.html",));
// });
// serving the static files
// app.use(express.static(path.join(__dirname, "../", "client/", "build")));
// app.use(express.static(path.join(__dirname, "images")));
module.exports = app;