Skip to content

Commit f825f3c

Browse files
committed
[Durable Objects] Add example to transactionSync().
1 parent 7ebe21f commit f825f3c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/content/docs/durable-objects/api/storage-api.mdx

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,41 @@ The `put()` method returns a `Promise`, but most applications can discard this p
207207

208208
* The callback must complete synchronously, that is, it should not be declared `async` nor otherwise return a Promise. Only synchronous storage operations can be part of the transaction. This is intended for use with SQL queries using [`ctx.storage.sql.exec()`](#sqlexec), which complete sychronously.
209209

210+
```ts
211+
// Transfer money from one account to another. It's
212+
// important that either both accounts are updated
213+
// or neither is!
214+
async transfer(amount, fromAcct, toAcct) {
215+
// Open a transaction, so either all changes apply or
216+
// none do.
217+
ctx.storage.transactionSync(() => {
218+
// Fetch both account balances.
219+
let account1 = ctx.storage.sql.exec(
220+
"SELECT balance FROM accounts WHERE id = ?", fromAcct)
221+
.one();
222+
let account2 = ctx.storage.sql.exec(
223+
"SELECT balance FROM accounts WHERE id = ?", toAcct)
224+
.one();
225+
226+
// Verify there's enough money in the account.
227+
if (account1.balance < amount) {
228+
// Throwing an error rolls back the transaction.
229+
// (Though in this example there's no changes to roll
230+
// back yet.)
231+
throw new Error("Not enough money in account.");
232+
}
233+
234+
// Update both account balances.
235+
ctx.storage.sql.exec(
236+
"UPDATE accounts SET balance = ? WHERE id = ?",
237+
account1.balance - amount, fromAcct);
238+
ctx.storage.sql.exec(
239+
"UPDATE accounts SET balance = ? WHERE id = ?",
240+
account2.balance + amount, toAcct);
241+
});
242+
}
243+
```
244+
210245
### sync
211246

212247
* `sync()` : <Type text='Promise' />

0 commit comments

Comments
 (0)