tangled
alpha
login
or
join now
timtinkers.online
/
discord-qotd-webhook
1
fork
atom
posts "question of the day" to a discord webhook
1
fork
atom
overview
issues
pulls
pipelines
kv.atomic to mitigate accidental double posts
timtinkers.online
7 months ago
8612e3ac
0bc8d517
0/1
deploy.yaml
failed
1m 1s
+19
-9
1 changed file
expand all
collapse all
unified
split
main.ts
+19
-9
main.ts
reviewed
···
10
10
11
11
// @ts-ignore Deno.cron is unstable, run with --unstable-cron flag
12
12
Deno.cron("QOTD", Deno.env.get("CRON_STRING"), async () => {
13
13
-
// Open KV and get last index
13
13
+
// Fetch data
14
14
+
const response = await fetch(endpoint);
15
15
+
const { data } = await response.json();
16
16
+
17
17
+
// Open KV and fetch last index
14
18
// @ts-ignore Deno.openKv is unstable, run with --unstable-kv flag
15
19
const kv = await Deno.openKv(
16
20
// `https://api.deno.com/databases/${
17
21
// Deno.env.get("DENO_KV_DATABASE_ID")
18
22
// }/connect`,
19
23
);
20
20
-
const result = await kv.get<number>(["lastIndex"]);
21
21
-
let index = result.value ?? 0;
24
24
+
const current = await kv.get<number>(["lastIndex"]);
25
25
+
const index = current.value ?? 0;
26
26
+
const nextIndex = (index + 1) % data.length;
22
27
23
23
-
const response = await fetch(endpoint);
24
24
-
const { data } = await response.json();
28
28
+
// Perform atomic operation to update index
29
29
+
const result = await kv.atomic()
30
30
+
.check(current) // Ensure the value hasn't changed
31
31
+
.set(["lastIndex"], nextIndex)
32
32
+
.commit();
25
33
34
34
+
if (!result.ok) {
35
35
+
console.log("Another instance already updated the index, skipping");
36
36
+
return;
37
37
+
}
38
38
+
39
39
+
// Post to Discord webhook
26
40
await sendDiscordNotification(data[index].question);
27
41
console.log(`Cron: posted question of index ${index} to Discord.`);
28
28
-
29
29
-
// Update last index in KV
30
30
-
index = (index + 1) % data.length;
31
31
-
await kv.set(["lastIndex"], index);
32
42
});