Implement a unit of work for transactions
Implement a unit of work for transactions in JavaScript: collect changes and commit them together or roll all back. Node.js 24.
A unit of work groups several changes into one transaction. The caller passes a function, and the helper commits if it finishes and rolls back if it throws.
import { DatabaseSync } from 'node:sqlite';
const db = new DatabaseSync(':memory:');
db.exec('CREATE TABLE accounts (name TEXT PRIMARY KEY, balance INTEGER)');
db.exec("INSERT INTO accounts VALUES ('a', 100), ('b', 0)");
function unitOfWork(work) {
db.exec('BEGIN');
try {
const result = work(db);
db.exec('COMMIT');
return result;
} catch (error) {
db.exec('ROLLBACK');
throw error;
}
}
const transfer = (from, to, amount) => unitOfWork((tx) => {
tx.prepare('UPDATE accounts SET balance = balance - ? WHERE name = ?').run(amount, from);
tx.prepare('UPDATE accounts SET balance = balance + ? WHERE name = ?').run(amount, to);
const left = tx.prepare('SELECT balance FROM accounts WHERE name = ?').get(from).balance;
if (left < 0) throw new Error('insufficient funds');
});
transfer('a', 'b', 40);
try { transfer('a', 'b', 500); } catch (error) { console.log(error.message); }
console.log(db.prepare('SELECT * FROM accounts ORDER BY name').all().map((r) => `${r.name}=${r.balance}`));insufficient funds
[ 'a=60', 'b=40' ]The failed transfer changed both rows and then rolled back, so balances show only the first transfer. Callers cannot forget the COMMIT or the ROLLBACK, and the business rule lives next to the writes it protects.
The helper is synchronous because node:sqlite is. With an async driver, await the work before committing and use one connection for the whole transaction.