-
Notifications
You must be signed in to change notification settings - Fork 1
/
aocFetch.js
62 lines (55 loc) · 1.79 KB
/
aocFetch.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
const { readFileSync, writeFileSync } = require('fs');
const fetch = require('node-fetch');
const { getDummyBoard } = require("./test/dummyBoard");
const {
KEEP_ALL_LEADERBOARDS,
DUMMY_BOARD,
DONT_USE_PERMANENT_STORAGE
} = require("./configHelper");
const { config } = require('./configHelper');
const boardUrl = config.leaderboardUrl;
const jsonBoardUrl = boardUrl + '.json';
let lastLeaderBoard = '{}';
function getLastLeaderBoard() {
try {
if (DONT_USE_PERMANENT_STORAGE || DUMMY_BOARD) {
return lastLeaderBoard;
} else {
return readFileSync('./data/aocleaderboard.json', { encoding: 'utf8' })
}
} catch {
return '{}';
}
}
async function fetchLeaderBoard() {
console.log(`Requesting leaderboard from [${ boardUrl }]`)
const requestInit = {
headers: {
'Cookie': config.aocCookie
}
};
const response = await fetch(jsonBoardUrl, requestInit);
const responseText = await (response).text();
return responseText;
}
async function getNewLeaderBoard() {
const newLeaderBoardJson = DUMMY_BOARD ? getDummyBoard() : await fetchLeaderBoard();
if (newLeaderBoardJson.startsWith('{') && JSON.parse(newLeaderBoardJson).members) {
if (DONT_USE_PERMANENT_STORAGE || DUMMY_BOARD) {
lastLeaderBoard = newLeaderBoardJson;
} else {
if (KEEP_ALL_LEADERBOARDS) {
writeFileSync(`./data/old/aocleaderboard-${ Date.now() }.json`, getLastLeaderBoard());
}
writeFileSync('./data/aocleaderboard.json', newLeaderBoardJson);
}
} else {
throw Error('Bad leaderboard response:' + newLeaderBoardJson);
}
return newLeaderBoardJson;
}
module.exports = {
boardUrl,
getLastLeaderBoard,
getNewLeaderBoard,
}