generated from adityabhagat007/Backend-templete-node-express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
94 lines (76 loc) · 2.08 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
import express from "express";
import compression from "compression";
import rateLimit from "express-rate-limit";
import helmet from "helmet";
import logger from "morgan";
import cors from "cors";
import xss from "xss-clean";
import hpp from "hpp";
import mongoSanitize from "express-mongo-sanitize";
import { fileURLToPath } from "url";
import path, { dirname } from "node:path";
import { globalErrorHandler } from "./src/v1/utils/errorHandler.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
import testApis from "./src/v1/routes/test-route.js";
import authApis from "./src/v1/routes/auth-routes.js";
import userApis from "./src/v1/routes/user-routes.js";
import tagApis from "./src/v1/routes/tag-routes.js";
//app and middleware
const app = express();
app.use(cors());
app.use(helmet());
app.use(
express.static(path.join(__dirname, "public"), {
setHeaders: function (res, path, stat) {
res.set("x-timestamp", Date.now().toString());
},
})
);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Data sanitization against NoSQL query injection
app.use(
mongoSanitize({
onSanitize: ({ req, key }) => {
console.warn(`This request[${key}] is sanitized`, req);
},
})
);
// Data sanitization against XSS
app.use(xss());
// Prevent parameter pollution
app.use(
hpp({
whitelist: [
"duration",
"ratingsQuantity",
"ratingsAverage",
"maxGroupSize",
"difficulty",
"price",
],
})
);
app.use(compression());
// Limit requests from same API
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: "Too many requests from this IP, please try again in an hour!",
});
app.use(limiter);
app.use("/api/v1/test", testApis);
app.use("/api/v1/auth", authApis);
app.use("/api/v1/user", userApis);
app.use("/api/v1/tag", tagApis);
// ERROR HANDLING MIDDLEWARE
app.use(globalErrorHandler);
// 404 MIDDLEWARE
app.use((req, res, next) => {
res.status(404).json({
message: "resource not found",
});
});
export default app;