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 all commits
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
22 changes: 19 additions & 3 deletions examples/kv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,29 @@ 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
await kv.atomic()
const res = await kv.atomic()
.check(atomicCheck)
.mutate({
type: "sum",
key: aliceScoreKey,
value: new Deno.KvU64(10n),
})
.commit();
const newScore = (await kv.get<Deno.KvU64>(aliceScoreKey)).value;
console.log("Alice's new score is: ", newScore);
// Check if the transaction was successful
if (res.ok) {
const newScore = (await kv.get<Deno.KvU64>(aliceScoreKey)).value;
console.log("Alice's new score is:", newScore);
} else {
console.error("Transaction failed ");
// Optionally, implement retry logic or handle the conflict
}
Loading