-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
53 lines (47 loc) · 1.6 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
const express = require("express")
const app = express();
const axios = require('axios');
var cache = {
lastUpdated: Date.now(),
data: {}
}
updateCache();
function updateCache() {
return new Promise(resolve => {
axios.get('http://kissmp.online:3692/latest', {timeout: 1000}).then(apiRequest => {
console.log("api is succeeding");
cache.lastUpdated = Date.now();
cache.data = {
servers: sortByPlayercount(apiRequest.data)
};
resolve();
})
.catch((err) => {
console.log("Api is failing");
if (!cache.data.servers) {
cache.data.servers = {none: true}
};
cache.data.error = err.code || true;
cache.data.age = cache.lastUpdated;
resolve();
})
});
};
app.use(express.static(__dirname + '/public', {
extensions: ['html']
}));
app.get("/getData", async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // Allow the api to be accessed from other domains.
res.setHeader('Cache-Control', 'no-store'); // Tells the browser not to cache this request.
if (cache.lastUpdated < Date.now() - 4000) {
await updateCache();
console.log("cache updated");
}
res.send(cache.data);
});
app.listen(4001);
function sortByPlayercount(servers) {
let serversArray = Object.entries(servers); // make an array of the servers so that we're able to use the sort function.
serversArray.sort((a, b) => b[1].player_count - a[1].player_count);
return Object.fromEntries(serversArray);
}