-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
103 lines (82 loc) · 2.4 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
95
96
97
98
99
100
101
102
103
const cors = require("cors");
const compression = require("compression");
const expressSession = require("express-session");
const express = require("express");
const path = require("path");
const morgan = require("morgan");
const spotifyRouter = require("./routes/spotifyRoutes");
const app = express();
require("dotenv").config();
// view Engine
app.set("view engine", "pug");
app.set("views", path.join(__dirname, "views"));
app.use(cors());
app.use(morgan("dev"));
app.use(
express.json({
limit: "50kb",
})
);
app.use(
expressSession({
secret: [process.env.SECRET_SESSION, "secret-session"],
resave: false,
saveUninitialized: false,
})
);
// Serving static files
app.use(express.static(path.join(__dirname, "public")));
// Compressing text responses
app.use(compression());
app.use("/", spotifyRouter);
// Error handling
app.use((req, res, next) => {
const err = new Error("Not Found");
err.status = 404;
next(err);
});
/////// GLOBAL ERROR HANDLING ////////////////
// error handler
app.use((err, req, res, next) => {
if (!err.message) {
err.message =
process.env.NODE_ENV === "development" ? err.message : "Please refresh or login again!";
}
// Production
const errProd = new Error("Something went wrong");
// Makes sure the error message is accessible in the PUG template.
res.locals.error = process.env.NODE_ENV === "development" ? err : errProd;
const { message } = err;
console.log(err);
// render the error page
res.status(err.status || 500);
if (
err.message ===
"Data is not found!! Please listen to some music or turn off private mode in Settings!"
) {
return res.redirect("/dataErr");
}
res.render("error", {
message,
});
});
const port = process.env.PORT;
const server = app.listen(port, () => {
console.log(`Listening on port ${port}...`);
});
process.on("unhandledRejection", (err) => {
console.log(err.name, err.message, err.stack);
console.log("Shutting down gracefully");
// Shut down the server, then slowly shut down the application, so that there are no outgoing or expecting responses.
server.close(() => {
process.exit(1);
});
});
process.on("uncaughtException", (err) => {
console.log(err.name, err.message, err.stack);
console.log("UNCAUGHT EXCEPTION 🤯");
console.log("Shutting down gracefully");
// Happens synchronously, no need of any server.
process.exit(1);
});
module.exports = app;