This repository was archived by the owner on Oct 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (69 loc) · 1.88 KB
/
server.js
File metadata and controls
73 lines (69 loc) · 1.88 KB
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 express = require("express");
const config = require("./config.js");
const calculateStandings = require("./calc");
const app = express();
app.use(express.json());
const TOKEN_TYPE = "Bearer";
app.use((req, res, next) => {
if (req.url === "/") {
return res.json({
successful: true,
message: "Service running",
});
}
try {
if (
req.headers.authorization.startsWith(TOKEN_TYPE + " ") &&
config.accepted_auth_tokens.includes(
req.headers.authorization.slice(TOKEN_TYPE.length + 1)
)
) {
return next();
} else {
throw new Error("");
}
} catch {
return res.status(401).json({
successful: false,
message: "Unauthorized",
});
}
});
app.post("/calc", (_req, res) => {
try {
runFunctionAtMostOncePerInterval(calculateStandings, config.calc_interval);
} catch {}
res.status(200).json({
successful: true,
message: "Calculating standings...",
});
});
function now() {
return Math.floor(Date.now() / 1000);
}
// calculate standings once when starting server (might have been offline some time)
calculateStandings();
let lastExecution = now();
let alreadyScheduled = false;
function runFunctionAtMostOncePerInterval(func, intervalInSeconds = 60) {
if (alreadyScheduled) {
// execution already scheduled, will happen shortly
} else if (now() - lastExecution > intervalInSeconds) {
// last execution happened already some time ago -> execute directly
func();
lastExecution = now();
} else {
// wait some time before executing function
alreadyScheduled = true;
setTimeout(() => {
func();
lastExecution = now();
alreadyScheduled = false;
}, Math.max(1, 1000 * (intervalInSeconds - (now() - lastExecution))));
}
}
app.listen(config.port, () => {
console.log(
`rcjberlin-evaluation listening at port http://localhost:${config.port}`
);
});