-
Notifications
You must be signed in to change notification settings - Fork 15
/
server.js
71 lines (61 loc) · 1.69 KB
/
server.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
const express = require("express");
const app = express();
const port = 3000;
const path = require("path");
const { allQuotes } = require("./taylorquotes");
app.use(express.static("views"));
String.prototype.toTitleCase = function () {
return this.replace(/\w\S*/g, (w) =>
w.replace(/^\w/, (c) => c.toUpperCase())
);
};
function getRandomElementFrom(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function setHeaderInformation(res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type"
);
}
// Filter allQuotes by the request parameters (if any)
function getFilteredQuotes(req) {
if (req.query?.song) {
return allQuotes.filter(
(lyrics) => lyrics.song === req.query.song.toTitleCase()
);
}
if (req.query?.album) {
return allQuotes.filter(
(lyrics) => lyrics.album === req.query.album.toTitleCase()
);
}
// No request parameters (filters), so use default value of allQuotes
return allQuotes;
}
// index
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname + "/index.html"));
});
// get random lyrics
app.get("/get", (req, res) => {
setHeaderInformation(res);
res.send(getRandomElementFrom(getFilteredQuotes(req)));
});
// get all lyrics that match with the filters
app.get("/get-all", (req, res) => {
setHeaderInformation(res);
res.send(getFilteredQuotes(req));
});
app.listen(process.env.PORT || port, function () {
console.log(
`Express server listening on port ${this.address().port} in ${
app.settings.env
} mode`
);
});