Transactions on a board
A small board with three columns. Moving a card updates the card and adds an activity row, and both go to the server in one request. Turn on Make the server reject every write and move a card: the card and the activity row show at once, then both revert when the error arrives. Clear done deletes the Done cards one request at a time, and stops at the first write the server refuses.
Loading the example...
Run locally
npx tiged BetterTyped/hyper-fetch/examples/db/transactions hyper-fetch-db-transactions && cd hyper-fetch-db-transactions && npm install && npm run devWhat it shows
- A named transaction:
moveis declared increateDb({ ... }, { transactions }). ItsmutationFnsends every write as onePOST /board/transactionsrequest. - The writes the server receives: the log shows the payload, an idempotency key and a list of
TransactionWriteobjects withcollection,op,keyandvalues. - All or nothing: when the request fails, the card update and the activity insert revert together.
- An unnamed transaction:
db.transaction((tx) => { ... })sends each write through its collection'smutate, in order. A failure reverts that write and drops the writes after it. - No rollback code: a transaction resolves with
{ success, error }and never throws.
How it works
db.tsdefines two collections,cardandactivity. The card collection declares onlydeleteand the activity collection onlyinsert, the writes that the unnamed transaction sends one by one.- The named transaction
movebuilds its own request withapplyWrites.setPayload({ idempotencyKey: id, mutations }). That is why it can update cards, although the card collection declares noupdate. moveCardinApp.tsxcallsdb.transaction("move", (tx) => { ... })with a card update and an activity insert. Both rows change on screen in one optimistic layer. The activity row gets its key fromcrypto.randomUUID(), because an insert in a transaction needs its key.- The fake server applies the list of writes in one go, or none of them. On success the db keeps the changes as the server state. On failure it removes both.
clearDoneuses an unnamed transaction. The server refuses to delete the signed contract, so the first delete succeeds and stays, the contract reverts, and the next delete and the activity insert are dropped without a request. The card list refetches, so the board shows what the server really stored.
When to use it
- Use a named transaction when the backend can apply several writes atomically, in one endpoint.
- Use an unnamed transaction when each write has its own endpoint, and showing them together is what matters.
- Use plain writes when the changes are independent of each other.
Related
Summary
You grouped a card move and its activity row into one named transaction sent as one request, and cleared a column with an unnamed transaction that stops at the first refused write.