generated from tripleten-com/se_project_express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
72 lines (57 loc) · 1.77 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
require("dotenv").config();
const express = require("express");
const { errors } = require("celebrate");
const winston = require("winston");
const expressWinston = require("express-winston");
const { PORT = 3001 } = process.env;
const mongoose = require("mongoose");
const cors = require("cors");
const routes = require("./routes");
const errorHandler = require("./middlewares/error-handler");
const { requestLogger } = require("./middlewares/logger");
const app = express();
app.use((req, res, next) => {
console.log("Incoming request:", req.method, req.url);
next();
});
// Middleware
console.log("Applying CORS middleware...");
app.use(cors());
console.log("Applying JSON middleware...");
app.use(express.json());
// Database
console.log("Connecting to database...");
mongoose
.connect("mongodb://127.0.0.1:27017/wtwr_db")
.then(() => console.log("Connected to DB"))
.catch((e) => console.log("DB error", e));
// Enable request logger right before the routes
app.use(requestLogger);
// Crash Test Route
app.get("/crash-test", () => {
setTimeout(() => {
throw new Error("Server will crash now");
}, 0);
});
// Routes
console.log("Applying routes...");
app.use(routes);
// Enable the error logger right after the routes
app.use(
expressWinston.errorLogger({
transports: [new winston.transports.File({ filename: "error.log" })],
format: winston.format.json(),
}),
);
// Celebrate Error Handling Middleware
console.log("Applying Celebrate error-handling middleware...");
app.use(errors());
// Centralized Error Handling Middleware
console.log("Applying custom error-handling middleware...");
app.use(errorHandler);
// Server
app.listen(PORT, "0.0.0.0", () => {
console.log(`App listening at ${PORT}`);
console.log("Server setup complete");
});
module.exports = app;