-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (52 loc) · 1.73 KB
/
index.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
const express = require('express');
const fs = require('fs');
const app = express();
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`listening at port ${port}`));
app.use(express.static('public'));
app.use(express.json())
// read and write files in node tutorial:
// https://stackabuse.com/reading-and-writing-json-files-with-node-js/
function readJSON(path) {
let data = fs.readFileSync(path);
let highscore = JSON.parse(data);
return highscore;
}
function writeJSON(path, json_string) {
fs.writeFileSync(path, json_string);
}
function updateHighscore(highscore, contender) {
// keys are automatically sorted
for (placement of Object.keys(highscore)) {
if (contender['score'] > Object.keys(highscore[placement])[0]) {
let new_placement = {}
new_placement[contender['score']] = contender['name'];
highscore[placement] = new_placement;
return { 'placement': placement, 'highscore': highscore };
}
}
return { 'placement': null, 'highscore': highscore };
}
// GET method route
app.get('/api/get', (request, response) => {
console.log('GET request received')
const path = 'private/highscore.json';
const highscore = readJSON(path);
response.json({
status: 'success',
msg: highscore
})
});
// POST method route
app.post('/api/post', (request, response) => {
console.log('POST request received')
const contender = request.body
const path = 'private/highscore.json';
const highscore = readJSON(path);
const updates = updateHighscore(highscore, contender);
writeJSON(path, JSON.stringify(updates['highscore']));
response.json({
status: 'success',
msg: updates
})
});