type Thread = {
lastUpdated: string
posts: unknown[]
}
const kv = await Deno.openKv()
async function createThread(id: string, thread: Thread) {
await kv.atomic()
.check({
key: ["threads", id],
versionstamp: null
})
.set(["threads", id], thread)
.set(["threads", "last_updated", thread.lastUpdated, id], thread)
.commit()
}
async function updateThread(id: string, thread: Thread) {
// Get the current thread value
const currentThread = await kv.get<Thread>(["threads", id])
if (!currentThread.value) {
// ...do something
return
}
// Set the new thread entry
const atomic = kv.atomic()
atomic.set(["threads", id], thread)
// Delete any existing index entries
const iter = kv.list({ prefix: ["threads", "last_updated", currentThread.value.lastUpdated] })
for await (const { key } of iter) {
atomic.delete(key)
}
// Set the new index entry
await atomic
.set(["threads", "last_updated", thread.lastUpdated, id], thread)
.commit()
}