posts "question of the day" to a discord webhook

kv.atomic to mitigate accidental double posts

+19 -9
+19 -9
main.ts
··· 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 - // Open KV and get last index 13 + // Fetch data 14 + const response = await fetch(endpoint); 15 + const { data } = await response.json(); 16 + 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 - const result = await kv.get<number>(["lastIndex"]); 21 - let index = result.value ?? 0; 24 + const current = await kv.get<number>(["lastIndex"]); 25 + const index = current.value ?? 0; 26 + const nextIndex = (index + 1) % data.length; 22 27 23 - const response = await fetch(endpoint); 24 - const { data } = await response.json(); 28 + // Perform atomic operation to update index 29 + const result = await kv.atomic() 30 + .check(current) // Ensure the value hasn't changed 31 + .set(["lastIndex"], nextIndex) 32 + .commit(); 25 33 34 + if (!result.ok) { 35 + console.log("Another instance already updated the index, skipping"); 36 + return; 37 + } 38 + 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 - 29 - // Update last index in KV 30 - index = (index + 1) % data.length; 31 - await kv.set(["lastIndex"], index); 32 42 });