Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add check to atomic op in kv example #1147

Merged
merged 6 commits into from
Nov 19, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: add versionstamp to enforce atomicity
  • Loading branch information
adit-bala committed Nov 19, 2024
commit 480d1989fd5eb825446c1d764d3c4ba1fad60a7a
12 changes: 11 additions & 1 deletion examples/kv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,19 @@ await kv.delete(["players", "carlos"]);
const aliceScoreKey = ["scores", "alice"];
await kv.set(aliceScoreKey, new Deno.KvU64(0n));


// To prepare an atomic transaction to update the score, first we need to
// check if the score has been modified since we read it. We can use the
// versionstamp to check if the value has been modified since we read it.
const aliceScoreEntry = await kv.get<Deno.KvU64>(aliceScoreKey);
const atomicCheck = {
key: aliceScoreEntry.key,
versionstamp: aliceScoreEntry.versionstamp,
};

// Add 10 to the player's score in an atomic transaction
const res = await kv.atomic()
.check({ key: aliceScoreKey, versionstamp: null }) // Check if this key has been modified since we read it
.check(atomicCheck)
.mutate({
type: "sum",
key: aliceScoreKey,
Expand Down