-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.js
73 lines (59 loc) · 1.73 KB
/
handlers.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
const fs = require('fs/promises');
const getScores = async (_, res) => {
try {
const data = JSON.parse(await fs.readFile(__dirname + '/resources/high-scores.json'));
res.status(200).json(data);
} catch (error) {
console.log(error);
res.status(500).send('Error');
}
}
const saveScore = async (req, res) => {
try {
const entry = req.body;
const data = JSON.parse(await fs.readFile(__dirname + '/resources/high-scores.json'));
for (let i = 0; i < data.length; i++) {
if (data[i].score < entry.score) {
data.splice(i, 0, entry);
data.pop();
await fs.writeFile(__dirname + '/resources/high-scores.json', JSON.stringify(data));
break;
}
}
res.status(200).json(data);
} catch (error) {
console.log(error);
res.status(500).send('Error');
}
}
const checkHighScore = async (req, res) => {
try {
const score = req.body.score;
const data = JSON.parse(await fs.readFile(__dirname + '/resources/high-scores.json'));
isHighScore = false;
for (let i = 0; i < data.length; i++) {
if (data[i].score < score) {
isHighScore = true;
break;
}
}
res.status(200).json({ isHighScore });
} catch (error) {
console.log(error);
res.status(500).send('Error');
}
}
const getHomePage = async (req, res) => {
try {
res.sendFile(__dirname + '/index.html');
} catch (error) {
console.log(error);
res.status(500).send('Error');
}
}
module.exports = {
getScores,
saveScore,
checkHighScore,
getHomePage
}