Design Patterns in Plain Words / Module 07

Module 7: Talking to the Database

Repository and Unit of Work in TypeScript, with node:sqlite, and how they differ from Data Mapper and Active Record.

Leo forwarded an email from Ben. Ben had paid for two seats, but his ticket showed only one. Maya opened the database. Ben’s order said “paid”, his payment was stored, and seat A2 belonged to Ana.

Maya, Leo and TinyTickets are invented, and so are the numbers in their story.

The checkout wrote three tables one row at a time, so a failure in the middle left half an order behind. And the SQL sat inside route handlers, so Maya couldn’t test the checkout rules without a database and a running server. This module teaches the two patterns that fix those problems, Repository and Unit of Work, and how they differ from Data Mapper and Active Record.

After this module, you can:

  • move SQL out of route handlers behind an OrderRepository interface, and test a rule with a plain-object fake
  • wrap several writes in one transaction with withTransaction, and say what commit and rollback do
  • tell Repository from Unit of Work, and Data Mapper from Active Record, in one sentence each
  • say when a plain function with one SQL query is enough, and no pattern is needed

Set up SQLite for the examples

Use the folder from Module 1, with the same package.json, tsconfig.json and tools. Save this file as db.ts, because every example in the module starts from it:

import { DatabaseSync } from "node:sqlite";

// An in-memory SQLite database with the TinyTickets tables
export function openDb(): DatabaseSync {
  const db = new DatabaseSync(":memory:");
  db.exec(`
    CREATE TABLE orders (
      id TEXT PRIMARY KEY, show_id TEXT NOT NULL, buyer_email TEXT NOT NULL,
      quantity INTEGER NOT NULL, total_cents INTEGER NOT NULL, status TEXT NOT NULL);
    CREATE TABLE payments (order_id TEXT PRIMARY KEY, charge_id TEXT NOT NULL);
    CREATE TABLE seats (
      show_id TEXT NOT NULL, seat TEXT NOT NULL, order_id TEXT NOT NULL,
      PRIMARY KEY (show_id, seat));
  `);
  return db;
}

// Prints what each table holds, one line per table
export function dump(db: DatabaseSync): void {
  const list = (sql: string) =>
    db.prepare(sql).all().map((row) => Object.values(row).join(" ")).join(", ");
  console.log("orders:  ", list("SELECT id, status FROM orders"));
  console.log("payments:", list("SELECT order_id, charge_id FROM payments"));
  console.log("seats:   ", list("SELECT seat, order_id FROM seats"));
}

The file uses SQLite, a database engine that keeps a whole database in one file or in memory, inside your own process. So no database server is needed. Node.js 24 ships SQLite as the built-in module node:sqlite, with no install and no command-line flag.

Every call is synchronous, so db.prepare(...).get(...) returns the row directly, not a promise. Node.js does nothing else while the query runs, and that’s fine for a small in-memory database in examples. ":memory:" gives a fresh, empty database that disappears when the process ends.

Each order also has a charge id, the id that the payment service returned for the buyer’s payment. The payment itself goes through PayClient from Module 1 before any code in this module runs. So this module only stores the charge id.

Repository: one place that knows how orders are stored

Two route handlers that both know the table

Buyers can look at an order, and they can cancel it while it’s still pending. Here is the code, orders-before.ts:

import express from "express";
import { openDb } from "./db.ts";

const db = openDb();
db.prepare("INSERT INTO orders VALUES (?, ?, ?, ?, ?, ?)")
  .run("o1", "spring", "ana@example.com", 2, 2550, "pending");

const app = express();

app.get("/orders/:id", (req, res) => {
  const row = db.prepare("SELECT * FROM orders WHERE id = ?").get(req.params.id);
  if (row === undefined) {
    res.status(404).json({ error: "no such order" });
    return;
  }
  const { id, show_id, total_cents, status } = row;
  res.json({ id, showId: show_id, totalCents: total_cents, status });
});

app.post("/orders/:id/cancel", (req, res) => {
  const row = db.prepare("SELECT * FROM orders WHERE id = ?").get(req.params.id);
  if (row === undefined) {
    res.status(404).json({ error: "no such order" });
    return;
  }
  if (row.status !== "pending") {
    res.status(409).json({ error: `cannot cancel a ${String(row.status)} order` });
    return;
  }
  db.prepare("UPDATE orders SET status = 'cancelled' WHERE id = ?").run(req.params.id);
  res.json({ id: row.id, status: "cancelled" });
});

app.listen(3000, () => console.log("TinyTickets listening on port 3000"));

Run it with npx tsx orders-before.ts. In a second terminal, send four requests:

curl -s localhost:3000/orders/o1
curl -s -X POST localhost:3000/orders/o1/cancel
curl -s -X POST localhost:3000/orders/o1/cancel
curl -s localhost:3000/orders/o9

curl prints one answer per request:

{"id":"o1","showId":"spring","totalCents":2550,"status":"pending"}
{"id":"o1","status":"cancelled"}
{"error":"cannot cancel a cancelled order"}
{"error":"no such order"}

Each ? is a placeholder, a slot that SQLite fills with a value safely. So a buyer can’t inject SQL through the id. db.prepare returns a prepared statement, a query that SQLite has read once and can run many times. .get() returns one row as an object with column names as keys, or undefined when no row matches.

Leo wrote, “A paid order must never be cancelled here, because the buyer would lose the money with no refund. Can you prove that?” Maya wanted a test for the rule. But the rule sits in the middle of a route handler, between two SQL calls. To test it, she needs a database with the table, a seeded row, a running server and an HTTP call.

The second problem shows in the code. Both handlers repeat the SELECT and read row.show_id and row.total_cents by column name. A third route would copy them again, and renaming one column means finding every copy.

Figure 1 shows what each handler knows. It also has the legend that every figure in the course uses.

(Buyer) --> [GET /orders/:id]            --> [db]  SELECT * FROM orders
(Buyer) --> [POST /orders/:id/cancel]    --> [db]  SELECT * FROM orders
                                         --> [db]  UPDATE orders ...
Both handlers know the SQL, the column names and the rules.

Legend, the same in every module
(Name)         a person
[name]         a module, function or class
[name] (I)     an interface: a shape that other code must fit
A --> B        A calls B
A ..> B        A implements B: A has the shape that interface B asks for
A ==> B        A creates B (with "new" or a factory function)
NEW            a part that the change added
~ await ~      the caller waits here; Node.js serves other work meanwhile

Figure 1: every handler that touches orders knows the table, so the rules can’t be tested without it.

Pause and predict: which lines would you move out of the handlers so that the cancel rule can run in a test with no database? What would the handlers call instead?

The idea: a collection of orders that hides the SQL

Repository comes from Martin Fowler’s book Patterns of Enterprise Application Architecture (2002). Domain objects are the things your business talks about, such as orders, shows and seats. A repository looks like a collection of domain objects, with methods such as findById and save, and it hides how and where they’re stored. So you can change the storage (the SQL, the columns, even the database) without touching the rules or the routes.

A library front desk works the same way. You ask for book 42, and the desk brings it. You never learn which shelf it was on, and the library can move its shelves without telling you. In the same way, cancelOrder asks OrderRepository for order o1 and never sees the SQL, as Figure 2 shows.

At the library
(Reader) --> [front desk]               --> [shelves]
             "book 42, please"              only the desk knows where it is

In TinyTickets
[cancelOrder] --> [OrderRepository] (I) --> [orders table]
                  findById("o1")            only the repository knows the SQL

Figure 2: the code asks the repository for an order, as a reader asks the desk for a book.

A library lends you the real book, but a repository hands you a copy, so only save changes the stored order.

The fix: an interface, a SQLite repository and a rule with no SQL

First, save the contract as types.ts:

export type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";

export interface Order {
  id: string;
  showId: string;
  buyerEmail: string;
  quantity: number;
  totalCents: number;
  status: OrderStatus;
}

// What the rest of the app may ask of stored orders, and nothing more
export interface OrderRepository {
  findById(id: string): Promise<Order | undefined>;
  save(order: Order): Promise<void>;
}

The methods return promises even though node:sqlite is synchronous. That’s because a database server such as PostgreSQL always answers later, and the interface should fit both. So callers always await.

Next, save the SQLite version as sqlite-order-repository.ts:

import type { DatabaseSync, SQLOutputValue } from "node:sqlite";
import type { Order, OrderRepository, OrderStatus } from "./types.ts";

const statuses: OrderStatus[] = ["pending", "paid", "cancelled", "refunded"];

// The only code that knows the column names of the orders table
export function toOrder(row: Record<string, SQLOutputValue>): Order {
  const status = statuses.find((s) => s === row.status);
  if (status === undefined) throw new Error(`order ${String(row.id)} has a bad status`);
  return {
    id: String(row.id),
    showId: String(row.show_id),
    buyerEmail: String(row.buyer_email),
    quantity: Number(row.quantity),
    totalCents: Number(row.total_cents),
    status,
  };
}

export function createSqliteOrderRepository(db: DatabaseSync): OrderRepository {
  const selectById = db.prepare("SELECT * FROM orders WHERE id = ?");
  const upsert = db.prepare("INSERT OR REPLACE INTO orders VALUES (?, ?, ?, ?, ?, ?)");
  return {
    async findById(id) {
      const row = selectById.get(id);
      return row === undefined ? undefined : toOrder(row);
    },
    async save(order) {
      const { id, showId, buyerEmail, quantity, totalCents, status } = order;
      upsert.run(id, showId, buyerEmail, quantity, totalCents, status);
    },
  };
}

Notice three things:

  • toOrder turns a row into an Order. A row arrives as Record<string, SQLOutputValue>, where each value can be a string, a number, null or another type. String() and Number() are safe here, because every column is NOT NULL with a fixed type. statuses.find returns a real OrderStatus or undefined, so no as cast is needed.
  • INSERT OR REPLACE is SQLite’s insert-or-update. When a row with the same primary key exists, SQLite deletes it and inserts the new one, as the SQLite conflict rules say. So save works for new and changed orders.
  • The statements are prepared once, when the repository is created, not on every call.

Now the rule, with no SQL and no HTTP. Save cancel-order.ts:

import type { Order, OrderRepository } from "./types.ts";

export type CancelResult =
  | { status: "cancelled"; order: Order }
  | { status: "notFound" }
  | { status: "refused"; reason: string };

// The business rule, with no SQL and no HTTP in it
export async function cancelOrder(
  orders: OrderRepository,
  id: string,
): Promise<CancelResult> {
  const order = await orders.findById(id);
  if (order === undefined) return { status: "notFound" };
  if (order.status !== "pending") {
    return { status: "refused", reason: `cannot cancel a ${order.status} order` };
  }
  const cancelled: Order = { ...order, status: "cancelled" };
  await orders.save(cancelled);
  return { status: "cancelled", order: cancelled };
}

CancelResult is a discriminated union, as in Module 1, a type whose status field tells TypeScript which shape it holds. So the route must handle all three outcomes. The routes move into app.ts, and they receive the repository from outside:

import express from "express";
import { cancelOrder } from "./cancel-order.ts";
import type { OrderRepository } from "./types.ts";

export function createApp(orders: OrderRepository): express.Express {
  const app = express();

  app.get("/orders/:id", async (req, res) => {
    const order = await orders.findById(req.params.id);
    if (order === undefined) {
      res.status(404).json({ error: "no such order" });
      return;
    }
    const { id, showId, totalCents, status } = order;
    res.json({ id, showId, totalCents, status });
  });

  app.post("/orders/:id/cancel", async (req, res) => {
    const result = await cancelOrder(orders, req.params.id);
    if (result.status === "notFound") res.status(404).json({ error: "no such order" });
    else if (result.status === "refused") res.status(409).json({ error: result.reason });
    else res.json({ id: result.order.id, status: result.order.status });
  });

  return app;
}

Last, main.ts is the composition root from Module 6, the one file that picks the real parts:

import { createApp } from "./app.ts";
import { openDb } from "./db.ts";
import { createSqliteOrderRepository } from "./sqlite-order-repository.ts";

// The composition root (Module 6): the one file that knows about SQLite
const orders = createSqliteOrderRepository(openDb());
await orders.save({
  id: "o1", showId: "spring", buyerEmail: "ana@example.com",
  quantity: 2, totalCents: 2550, status: "pending",
});

createApp(orders).listen(3000, () => console.log("TinyTickets listening on port 3000"));

Run npx tsx main.ts and send the same four curl requests. The server prints TinyTickets listening on port 3000, and curl prints the same four lines as before. Figure 3 shows how the structure changed.

Before
  [GET /orders/:id]          --> [DatabaseSync]  SQL, columns
  [POST /orders/:id/cancel]  --> [DatabaseSync]  SQL, columns, rule

After
  [main.ts] ==> [createSqliteOrderRepository] NEW
  [routes in app.ts] --> [cancelOrder] NEW --> [OrderRepository] (I) NEW
  [routes in app.ts] --> [OrderRepository] (I)
  [SQLite repository] ..> [OrderRepository] (I)   the only SQL is here
  [cancel-order.test.ts] ==> [fake repository] ..> [OrderRepository] (I)

Figure 3: the SQL moves into one object behind an interface, and routes and rules only see OrderRepository.

Prove it with a test

Now you can test Leo’s rule with no database at all. Save cancel-order.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import { cancelOrder } from "./cancel-order.ts";
import type { Order, OrderRepository } from "./types.ts";

// A fake repository: a plain object that keeps orders in a Map
function fakeOrders(rows: Map<string, Order>): OrderRepository {
  return {
    async findById(id) {
      return rows.get(id);
    },
    async save(order) {
      rows.set(order.id, order);
    },
  };
}

const ana: Order = {
  id: "o1", showId: "spring", buyerEmail: "ana@example.com",
  quantity: 2, totalCents: 2550, status: "paid",
};

test("a paid order is never cancelled", async () => {
  const rows = new Map([["o1", ana]]);
  const result = await cancelOrder(fakeOrders(rows), "o1");
  assert.deepEqual(result, { status: "refused", reason: "cannot cancel a paid order" });
  assert.equal(rows.get("o1")?.status, "paid");
});

test("a pending order is cancelled and saved", async () => {
  const pending: Order = { ...ana, status: "pending" };
  const rows = new Map([["o1", pending]]);
  const result = await cancelOrder(fakeOrders(rows), "o1");
  assert.equal(result.status, "cancelled");
  assert.equal(rows.get("o1")?.status, "cancelled");
});

Run it with npx tsx --test cancel-order.test.ts:

✔ a paid order is never cancelled (0.699792ms)
✔ a pending order is cancelled and saved (0.083333ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

The fake is a plain object with no implements. It fits OrderRepository because of structural typing from Module 1, where an object fits an interface when its shape is right. The “before” code couldn’t be tested this way, because its rule lived inside a route handler.

The next change: a door list for Leo

Leo asked for a list of buyers for one show, to check names at the door. With the repository, Maya adds one method to the contract, one query to the SQLite repository and one route. Here are the changed parts, marked NEW, as an excerpt from three files:

// types.ts, inside OrderRepository
  findByShow(showId: string): Promise<Order[]>; // NEW

// sqlite-order-repository.ts, inside createSqliteOrderRepository
  const selectByShow = db.prepare( // NEW
    "SELECT * FROM orders WHERE show_id = ? ORDER BY id",
  );
  // and in the returned object:
    async findByShow(showId) { // NEW
      return selectByShow.all(showId).map(toOrder);
    },

// app.ts, inside createApp
  app.get("/shows/:id/orders", async (req, res) => { // NEW
    const list = await orders.findByShow(req.params.id);
    res.json(list.map(({ id, buyerEmail, quantity }) => ({ id, buyerEmail, quantity })));
  });

With a second order for Ben saved in main.ts, curl -s localhost:3000/shows/spring/orders prints:

[{"id":"o1","buyerEmail":"ana@example.com","quantity":2},{"id":"o2","buyerEmail":"ben@example.com","quantity":4}]

The new query reuses toOrder, so the column names are still written in one place. cancelOrder didn’t change. But the fake in cancel-order.test.ts needs a findByShow too, or tsc reports that the fake no longer fits OrderRepository. So a bigger interface has a price, because every implementation must grow with it.

Use it when, skip it when

Use a repository when you see these signals in code:

  • the same SELECT or the same column names appear in two or more handlers
  • a business rule sits between SQL calls, and testing it needs a database
  • a route handler reads row.some_column and builds the response by hand

Skip it when:

  • one query is used in one place, such as a report script or a one-off admin task
  • the code is a thin pass-through with no rule to test: read a row, return it

The simpler option is a plain function next to the code that uses it, such as async function findOrder(db, id). Move it into a repository when a second caller or a rule appears.

The cost

  • More files and names. One route file became types.ts, sqlite-order-repository.ts, cancel-order.ts, app.ts and main.ts.
  • Indirection. “Go to definition” on orders.findById lands on the interface, so you must open main.ts to learn which repository runs.
  • A growing interface. Each new query is a new method in the interface, in the real repository and in every fake. A repository with dozens of methods is hard to fake.
  • Hidden SQL. The person who writes cancelOrder can’t see which queries run. So two repository calls in a loop can become hundreds of queries, and nothing in the rule shows it.
  • Runtime cost. Each query costs one extra function call and one promise. With a database server, that’s small next to the network trip.

Often confused with

  • Data Mapper (later in this module): the part that turns rows into objects, like toOrder. A repository usually uses a mapper and adds collection-style methods on top.
  • Unit of Work (next section): decides which writes must succeed or fail together. A repository decides where one kind of data lives.
  • Facade (Module 3): a simpler front for a complex subsystem. A repository is a facade over storage that also speaks in domain objects (Order), not rows.

Exercise: run the app with no database

Write memoryOrders() in memory-orders.ts, the name Module 3 gave its in-memory repository. It must keep orders in a Map and fit OrderRepository (the version without findByShow). Then make a copy of main.ts that uses it. Which lines of app.ts or cancel-order.ts must change?

Answer

memory-orders.ts:

import type { Order, OrderRepository } from "./types.ts";

// Keeps orders in a Map; the data is gone when the process stops
export function memoryOrders(): OrderRepository {
  const rows = new Map<string, Order>();
  return {
    async findById(id) {
      return rows.get(id);
    },
    async save(order) {
      rows.set(order.id, order);
    },
  };
}

main-memory.ts:

import { createApp } from "./app.ts";
import { memoryOrders } from "./memory-orders.ts";

const orders = memoryOrders(); // the only line that changed
await orders.save({
  id: "o1", showId: "spring", buyerEmail: "ana@example.com",
  quantity: 2, totalCents: 2550, status: "pending",
});

createApp(orders).listen(3000, () => console.log("TinyTickets listening on port 3000"));

No line of app.ts or cancel-order.ts changes. The same curl requests give the same answers, for example {"id":"o1","status":"cancelled"} for the first cancel. An in-memory repository like this is useful for demos and for tests of routes. But don’t use it in production, because every order is lost when the server restarts.

Unit of Work: several writes that succeed or fail together

A checkout that stores half an order

The checkout writes three kinds of rows: the order, a payment record with the charge id, and one row per seat. Maya already had a repository for each. The two new ones, for payments and seats, are in stores.ts:

import type { DatabaseSync } from "node:sqlite";

export interface PaymentRecord {
  orderId: string;
  chargeId: string;
}

export interface PaymentRepository {
  save(record: PaymentRecord): Promise<void>;
}

export interface SeatRepository {
  reserve(showId: string, seat: string, orderId: string): Promise<void>;
}

export function createSqlitePaymentRepository(db: DatabaseSync): PaymentRepository {
  const insert = db.prepare("INSERT INTO payments VALUES (?, ?)");
  return {
    async save(record) {
      insert.run(record.orderId, record.chargeId);
    },
  };
}

// The seats table has PRIMARY KEY (show_id, seat), so a taken seat throws
export function createSqliteSeatRepository(db: DatabaseSync): SeatRepository {
  const insert = db.prepare("INSERT INTO seats VALUES (?, ?, ?)");
  return {
    async reserve(showId, seat, orderId) {
      insert.run(showId, seat, orderId);
    },
  };
}

A constraint is a rule that the database itself enforces. PRIMARY KEY (show_id, seat) in db.ts is one, and it allows no second row for the same seat at the same show. The seat repository relies on it.

Here is the checkout, checkout-before.ts. Ana buys seats A1 and A2. Then Ben tries to buy A3 and A2, and A2 is already Ana’s:

import { dump, openDb } from "./db.ts";
import { createSqliteOrderRepository } from "./sqlite-order-repository.ts";
import { createSqlitePaymentRepository, createSqliteSeatRepository } from "./stores.ts";

const db = openDb();
const orders = createSqliteOrderRepository(db);
const payments = createSqlitePaymentRepository(db);
const seats = createSqliteSeatRepository(db);

type Checkout = {
  orderId: string; buyerEmail: string; seats: string[]; chargeId: string;
};

// Three kinds of writes; each one is stored the moment it runs
async function placeOrder(input: Checkout): Promise<void> {
  const quantity = input.seats.length;
  const totalCents = 1200 * quantity + (quantity >= 4 ? 0 : 150);
  const { orderId, buyerEmail, chargeId } = input;
  await orders.save({
    id: orderId, showId: "spring", buyerEmail, quantity, totalCents, status: "paid",
  });
  await payments.save({ orderId, chargeId });
  for (const seat of input.seats) await seats.reserve("spring", seat, orderId);
}

const ana = { orderId: "o1", buyerEmail: "ana@example.com", seats: ["A1", "A2"], chargeId: "ch_1" };
const ben = { orderId: "o2", buyerEmail: "ben@example.com", seats: ["A3", "A2"], chargeId: "ch_2" };

await placeOrder(ana);
try {
  await placeOrder(ben);
} catch (err: unknown) {
  if (err instanceof Error) console.log("checkout failed:", err.message);
}
dump(db);

Output of npx tsx checkout-before.ts:

checkout failed: UNIQUE constraint failed: seats.show_id, seats.seat
orders:   o1 paid, o2 paid
payments: o1 ch_1, o2 ch_2
seats:    A1 o1, A2 o1, A3 o2

The seat constraint did its job, so A2 still belongs to Ana. But Ben’s order o2 says “paid”, his payment record exists, and he holds A3 alone. That’s what Maya found in the opening scene.

Each save was stored the moment it ran, and nothing undid the first three writes when the fourth failed. Figure 4 lists the writes in order.

Ben's checkout, seats A3 and A2               stored?
1  orders.save(o2, "paid")                    yes
2  payments.save(o2, ch_2)                    yes
3  seats.reserve(A3)                          yes
4  seats.reserve(A2)    fails: Ana holds A2   no
Nothing undoes steps 1 to 3.

Figure 4: a failure at step 4 leaves the three earlier writes in the database.

The change request from Leo was short: “When a checkout fails, nothing of it should stay.” The repositories can’t help, because each one saves on its own. The code is also hard to test. placeOrder uses repositories created at the top of its file, so a test would need the real SQLite database.

Pause and predict: the database already offers one tool that makes several writes “all or nothing”. Where in placeOrder would it start, and where would it end? Who should own that start and end, placeOrder or something else?

The idea: one transaction boundary around the work

Unit of Work also comes from Fowler’s book. A unit of work makes a group of writes succeed together or fail together. The tool underneath is a database transaction, a group of statements that the database applies completely or not at all.

You start a transaction with BEGIN. COMMIT makes every write since BEGIN permanent. ROLLBACK throws all of them away, as if they never ran. SQLite’s transaction page describes the three commands.

So a unit of work lets you change which writes belong to one business action, without touching how each table is written.

A shop till works the same way. The cashier scans bread, milk and eggs. If your card is accepted, you leave with all three, and if it’s declined, you leave with none. In the same way, withTransaction keeps the order, payment and seat rows only if the work succeeds, as Figure 5 shows.

At the shop till                  In TinyTickets
[till] scans bread, milk, eggs   [withTransaction] runs order, payment, seats
card accepted --> all items sold work returns --> COMMIT: all rows stay
card declined --> no item sold   work throws  --> ROLLBACK: no row stays

Figure 5: like a till, the transaction keeps every write or none of them.

The fix: withTransaction

This module writes the unit of work as a function that takes the work as a callback. Save transaction.ts:

import type { DatabaseSync } from "node:sqlite";
import type { OrderRepository } from "./types.ts";
import { createSqliteOrderRepository } from "./sqlite-order-repository.ts";
import {
  createSqlitePaymentRepository, createSqliteSeatRepository,
  type PaymentRepository, type SeatRepository,
} from "./stores.ts";

// Everything a unit of work may write to
export interface Repositories {
  orders: OrderRepository;
  payments: PaymentRepository;
  seats: SeatRepository;
}

export type WithTransaction = <T>(work: (tx: Repositories) => Promise<T>) => Promise<T>;

export function createWithTransaction(db: DatabaseSync): WithTransaction {
  const tx: Repositories = {
    orders: createSqliteOrderRepository(db),
    payments: createSqlitePaymentRepository(db),
    seats: createSqliteSeatRepository(db),
  };
  return async (work) => {
    db.exec("BEGIN");
    try {
      const result = await work(tx);
      db.exec("COMMIT");
      return result;
    } catch (err) {
      db.exec("ROLLBACK");
      throw err;
    }
  };
}

WithTransaction is a generic function type, as in Module 1, so it returns whatever work returns. The work receives tx, the repositories it may write through. If the work throws, withTransaction rolls back and then rethrows the same error, so the caller still sees it. A rollback must never hide an error.

Now placeOrder takes withTransaction as a parameter and does its writes inside it. Save place-order.ts:

import type { Order } from "./types.ts";
import type { WithTransaction } from "./transaction.ts";

export type Checkout = {
  orderId: string; buyerEmail: string; seats: string[]; chargeId: string;
};

// The same three kinds of writes, now inside one transaction
export async function placeOrder(
  withTransaction: WithTransaction,
  input: Checkout,
): Promise<Order> {
  const quantity = input.seats.length;
  const totalCents = 1200 * quantity + (quantity >= 4 ? 0 : 150);
  const { orderId, buyerEmail, chargeId } = input;
  const order: Order = {
    id: orderId, showId: "spring", buyerEmail, quantity, totalCents, status: "paid",
  };
  return withTransaction(async (tx) => {
    await tx.orders.save(order);
    await tx.payments.save({ orderId, chargeId });
    for (const seat of input.seats) await tx.seats.reserve("spring", seat, orderId);
    return order;
  });
}

And the script that runs it, checkout-after.ts:

import { dump, openDb } from "./db.ts";
import { placeOrder } from "./place-order.ts";
import { createWithTransaction } from "./transaction.ts";

const db = openDb();
const withTransaction = createWithTransaction(db);

const ana = { orderId: "o1", buyerEmail: "ana@example.com", seats: ["A1", "A2"], chargeId: "ch_1" };
const ben = { orderId: "o2", buyerEmail: "ben@example.com", seats: ["A3", "A2"], chargeId: "ch_2" };

await placeOrder(withTransaction, ana);
try {
  await placeOrder(withTransaction, ben);
} catch (err: unknown) {
  if (err instanceof Error) console.log("checkout failed:", err.message);
}
dump(db);

Pause and predict: Ben’s checkout fails at seat A2 again. What does dump print for o2 this time?

Output of npx tsx checkout-after.ts:

checkout failed: UNIQUE constraint failed: seats.show_id, seats.seat
orders:   o1 paid
payments: o1 ch_1
seats:    A1 o1, A2 o1

Ana’s checkout gives the same rows as before. Ben’s failure prints the same error, but this time nothing of o2 stays.

Rule: A write made through tx stays only if the whole work returns; if the work throws, every write since BEGIN is gone.

Figure 6 follows Ben’s failing checkout.

1  [checkout-after.ts] --> [placeOrder]     Ben, seats A3 and A2
2  [placeOrder] --> [withTransaction]       work(tx)
3  [withTransaction] --> [db]               BEGIN
4  [work] --> [tx.orders] [tx.payments]     save o2, save ch_2
     ~ await ~
5  [work] --> [tx.seats]                    reserve A3, then A2: throws
6  [withTransaction] --> [db]               ROLLBACK: o2, ch_2 and A3 are gone
7  [withTransaction] rethrows; checkout-after.ts prints "checkout failed"

Figure 6: the error travels up through withTransaction, which rolls back before it lets the error go.

Prove it with a test

The test fake is a plain function that fits WithTransaction. Its writes wait in a list and reach stored only when the work succeeds. Save place-order.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import { placeOrder } from "./place-order.ts";
import type { Repositories, WithTransaction } from "./transaction.ts";

// A fake transaction: writes wait in `pending`, and reach `stored` only on success
function fakeTransaction(stored: string[], takenSeats: string[]): WithTransaction {
  return async (work) => {
    const pending: string[] = [];
    const tx: Repositories = {
      orders: {
        async findById() { return undefined; },
        async save(order) { pending.push(`order ${order.id}`); },
      },
      payments: {
        async save(record) { pending.push(`payment ${record.chargeId}`); },
      },
      seats: {
        async reserve(showId, seat) {
          if (takenSeats.includes(seat)) throw new Error(`seat ${seat} is taken`);
          pending.push(`seat ${seat}`);
        },
      },
    };
    const result = await work(tx);
    stored.push(...pending);
    return result;
  };
}

const ben = {
  orderId: "o2", buyerEmail: "ben@example.com", seats: ["A3", "A2"], chargeId: "ch_2",
};

test("a taken seat stores nothing for the whole order", async () => {
  const stored: string[] = [];
  const checkout = placeOrder(fakeTransaction(stored, ["A2"]), ben);
  await assert.rejects(checkout, /seat A2 is taken/);
  assert.deepEqual(stored, []);
});

test("a good checkout stores the order, the payment and every seat", async () => {
  const stored: string[] = [];
  await placeOrder(fakeTransaction(stored, []), ben);
  assert.deepEqual(stored, ["order o2", "payment ch_2", "seat A3", "seat A2"]);
});

The fake proves that every write goes through tx, and that an error isn’t swallowed. But it doesn’t prove that SQLite really rolls back. So one more short test checks that against a real database, which is cheap because ":memory:" needs no server. Save transaction.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import { openDb } from "./db.ts";
import { createWithTransaction } from "./transaction.ts";

test("withTransaction rolls back every write when the work throws", async () => {
  const db = openDb(); // a real SQLite database, in memory
  const withTransaction = createWithTransaction(db);
  const failing = withTransaction(async (tx) => {
    await tx.payments.save({ orderId: "o2", chargeId: "ch_2" });
    throw new Error("seat A2 is taken");
  });
  await assert.rejects(failing, /seat A2 is taken/);
  assert.deepEqual(db.prepare("SELECT * FROM payments").all(), []);
});

Run both with npx tsx --test place-order.test.ts transaction.test.ts:

✔ a taken seat stores nothing for the whole order (1.043125ms)
✔ a good checkout stores the order, the payment and every seat (0.157834ms)
✔ withTransaction rolls back every write when the work throws (1.384917ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0

The next change: queue the ticket email in the same transaction

Leo wanted the ticket email sent later by a worker, a separate process, so the buyer doesn’t wait for the email service. So the checkout adds a row to a new email_jobs table, and the worker reads that table and sends the emails. The job row must exist only if the order exists. Here are the changed parts, as an excerpt from five files:

// db.ts, inside openDb: one more table
    CREATE TABLE email_jobs (order_id TEXT NOT NULL, email TEXT NOT NULL);

// stores.ts: one more small repository
export interface EmailJobRepository {
  add(orderId: string, email: string): Promise<void>;
}

export function createSqliteEmailJobRepository(db: DatabaseSync): EmailJobRepository {
  const insert = db.prepare("INSERT INTO email_jobs VALUES (?, ?)");
  return {
    async add(orderId, email) {
      insert.run(orderId, email);
    },
  };
}

// transaction.ts: one more field in Repositories, and in tx
  emailJobs: EmailJobRepository; // NEW
    emailJobs: createSqliteEmailJobRepository(db), // NEW

// place-order.ts: one more line inside the transaction
    await tx.emailJobs.add(orderId, buyerEmail); // NEW

// place-order.test.ts: the fake gets the new field
      emailJobs: { async add(orderId, email) { pending.push(`job ${email}`); } }, // NEW

With dump printing the new table too, npx tsx checkout-after.ts prints:

checkout failed: UNIQUE constraint failed: seats.show_id, seats.seat
orders:   o1 paid
payments: o1 ch_1
seats:    A1 o1, A2 o1
jobs:     o1 ana@example.com

Ben’s failed checkout left no job behind, so no worker will email him tickets he doesn’t have. The BEGIN, COMMIT and ROLLBACK code didn’t change. The new write joined the transaction because it goes through tx.

Use it when, skip it when

Use a unit of work when:

  • one business action writes two or more rows, and a half-done action is wrong. Two examples are an order without its seats, and a seat change that frees the old seat but not the new one.
  • you see await repoA.save(...) followed by await repoB.save(...) with no transaction around them
  • you clean up half-written data by hand after failures

Skip it when:

  • the action writes one row. A single statement is already all or nothing.
  • the writes are independent, and a partial result is fine, such as logging page views

The simpler option for a single write is the repository call alone. For one function that needs a transaction once, db.exec("BEGIN") with try, COMMIT and ROLLBACK inline is fine. Move it into withTransaction when a second function needs it.

The cost

  • It covers one database only. The charge at the payment service happened before the transaction, and ROLLBACK can’t undo it. If the transaction fails after a charge, the code must refund it, or hold the seats first and charge afterwards.
  • Keep slow work out of the callback. This module’s SQLite setup has one connection. So if the work awaits a slow call, such as the seat-map service, a second request can run in the gap. Its BEGIN fails with “cannot start a transaction within a transaction”, and its plain writes would land inside your open transaction.
  • Locks. While a transaction is open, the database holds locks that can make other writers wait. So keep transactions short.
  • One more parameter. Every function that writes takes withTransaction or tx, and every fake must provide all the repositories in Repositories.

Often confused with

  • Repository: where one kind of data lives. Unit of Work: which writes belong together.
  • Command (Module 4): an action stored as an object to run later. Fowler’s class form of Unit of Work (in “Going deeper”) also stores changes to write later, but its point is all-or-nothing, not undo or a queue.

Exercise: the same seat twice

Ana’s browser sends seats ["A1", "A1"] by mistake, with order o1 and charge ch_1, into an empty database. Predict what dump(db) prints with the “before” placeOrder and with the “after” one.

Answer

Both print checkout failed: UNIQUE constraint failed: seats.show_id, seats.seat. Then the “before” version prints:

orders:   o1 paid
payments: o1 ch_1
seats:    A1 o1

The “after” version prints three empty tables:

orders:   
payments: 
seats:    

The second A1 breaks the primary key of seats. Before, the order, the payment and the first A1 were stored already. After, ROLLBACK removed all three.

Data Mapper and Active Record: who knows the SQL

Both patterns come from Fowler’s book, and both connect objects to rows. With Active Record, the object holds its row and saves itself, as in order.status = "cancelled" followed by await order.save(). With Data Mapper, the object is plain data, and a separate mapper moves it to and from the table. toOrder and the SQLite repository in this module are a small data mapper.

Figure 7 shows the two side by side.

Active Record                          Data Mapper
+-----------------------------+        +-----------------------------+
| [Order]                     |        | [Order]       plain data    |
|   id, status                |        |   id, status                |
|   save()   --> [db]         |        +-----------------------------+
|   cancel()                  |        | [toOrder + SQLite repo]     |
+-----------------------------+        |   rows in, rows out --> [db]|
                                       +-----------------------------+

Figure 7: in Active Record the object talks to the database, and in Data Mapper a separate part does.

You meet both in an ORM, a library that maps classes to tables and writes the SQL for you. TypeORM, an ORM for TypeScript, supports both styles. Its entities can extend BaseEntity and call save() on themselves, or stay plain and be saved through a Repository.

If you want to test rules on plain objects with no database, you want Data Mapper. But Active Record is fine for simple create-read-update-delete screens, where objects match tables one to one.

Side by side

The table compares the four ideas in this module.

Pattern The problem it solves What it lets you change Its cost
Repository SQL and column names spread through handlers; rules need a database to test The storage, without touching rules or routes More files; a growing interface; hidden queries
Unit of Work A failure in the middle leaves half-written data Which writes belong together, without touching how each is written One database only; slow awaits inside hurt; locks
Data Mapper Objects and tables have different shapes The table layout, without touching the objects Mapping code to keep in step with the table
Active Record Simple screens that map one object to one table Little: the object and its table change together Rules and SQL mix; tests need a database

Figure 8 is the decision figure for this module. It starts from the database code in front of you, and its first exit is “no pattern needed”.

You are writing code that reads or writes the database
  |
  v
One query, used in one place, with no rule to test? -- yes --> No pattern
  | no                                                         needed: a
  v                                                            plain function
Same table used from several places, or a rule that            with the SQL.
needs a database to test? -- yes --> Repository
  |
  v
Does one action write two or more rows that must all
stay or all go? -- yes --> Unit of Work: one transaction around them
  | no
  v
Repository calls alone are enough.

Figure 8: most database code needs a repository at most, and a transaction boundary only when several writes must agree.

Check yourself

  1. What does OrderRepository hide from cancelOrder, and what does it show?
  2. Why could cancel-order.test.ts pass a plain object where cancelOrder expects an OrderRepository?
  3. In Ben’s checkout, what does the database hold for order o2 after the seat fails, without and with withTransaction?
  4. What is the difference between Repository and Unit of Work, in one sentence each?
  5. Name one thing that ROLLBACK can’t undo in the TinyTickets checkout, and one case where you would skip the repository.
Answers
  1. It hides the SQL, the table and column names, and the database itself. It shows only domain operations on Order objects: findById and save.
  2. TypeScript uses structural typing. An object fits an interface if it has the right methods with the right types, with or without implements.
  3. Without it: the order o2 with status “paid”, the payment ch_2, and seat A3. With it: nothing for o2, because the transaction rolled back all three writes.
  4. A repository decides where one kind of data lives and hides how it’s stored. A unit of work decides which writes belong to one action and makes them succeed or fail together.
  5. The charge at the payment service, because it happened outside the database. Skip the repository for one query used in one place with no rule to test, such as a report script.

Lab: let buyers change a seat without losing it

Time: about 20 minutes. Start from the files of this module, including the email-jobs change, in one folder.

Here is the seat-change route, seat-change-before.ts. Ben holds A2 and A3, and Ana holds A1:

import express from "express";
import { openDb } from "./db.ts";

const db = openDb();
db.prepare("INSERT INTO orders VALUES (?, ?, ?, ?, ?, ?)")
  .run("o2", "spring", "ben@example.com", 2, 2550, "paid");
db.exec(`INSERT INTO seats VALUES
  ('spring', 'A1', 'o1'), ('spring', 'A2', 'o2'), ('spring', 'A3', 'o2')`);

const app = express();
app.use(express.json());

// Body: {"from":"A2","to":"B1"} moves one seat of the order
app.post("/orders/:id/seats", (req, res) => {
  const body: unknown = req.body;
  if (
    typeof body !== "object" || body === null ||
    !("from" in body) || typeof body.from !== "string" ||
    !("to" in body) || typeof body.to !== "string"
  ) {
    res.status(400).json({ error: "bad input" });
    return;
  }
  db.prepare("DELETE FROM seats WHERE show_id = 'spring' AND seat = ? AND order_id = ?")
    .run(body.from, req.params.id);
  db.prepare("INSERT INTO seats VALUES ('spring', ?, ?)").run(body.to, req.params.id);
  const rows = db.prepare("SELECT seat FROM seats WHERE order_id = ? ORDER BY seat")
    .all(req.params.id);
  res.json({ orderId: req.params.id, seats: rows.map((row) => row.seat) });
});

app.listen(3000, () => console.log("TinyTickets listening on port 3000"));

Run it, and send three changes for Ben: A2 to B1, then B1 to A1, then A1 to C1:

curl -s -X POST localhost:3000/orders/o2/seats -H 'content-type: application/json' -d '{"from":"A2","to":"B1"}'
curl -s -X POST localhost:3000/orders/o2/seats -H 'content-type: application/json' -d '{"from":"B1","to":"A1"}'
curl -s -X POST localhost:3000/orders/o2/seats -H 'content-type: application/json' -d '{"from":"A1","to":"C1"}'

The first answer is {"orderId":"o2","seats":["A3","B1"]}. The second is a 500 error page with UNIQUE constraint failed, because A1 is Ana’s, and B1 is gone from Ben’s order. The third answer is {"orderId":"o2","seats":["A3","C1"]}. So Ben gave away a seat he didn’t hold, and got C1 for it.

The change request from Leo: “A failed seat change must keep the old seat. Only paid orders may change seats. And nobody may move a seat they don’t hold.”

Refactor so that this test file, seat-change.test.ts, passes. Then write seat-change.ts, a server with the same route that uses your new code.

import { test } from "node:test";
import assert from "node:assert/strict";
import { changeSeat } from "./change-seat.ts";
import type { Order } from "./types.ts";
import type { Repositories, WithTransaction } from "./transaction.ts";

const unused = async (): Promise<never> => {
  throw new Error("changeSeat should not call this");
};

// `seats` maps each seat to the order that holds it; it changes only on success
function fakeTransaction(orders: Order[], seats: Map<string, string>): WithTransaction {
  return async (work) => {
    const draft = new Map(seats);
    const tx: Repositories = {
      orders: {
        async findById(id) { return orders.find((o) => o.id === id); },
        save: unused,
      },
      payments: { save: unused },
      emailJobs: { add: unused },
      seats: {
        async reserve(showId, seat, orderId) {
          if (draft.has(seat)) throw new Error(`seat ${seat} is taken`);
          draft.set(seat, orderId);
        },
        async release(showId, seat, orderId) {
          if (draft.get(seat) !== orderId) return false;
          return draft.delete(seat);
        },
      },
    };
    const result = await work(tx);
    seats.clear();
    for (const [seat, orderId] of draft) seats.set(seat, orderId);
    return result;
  };
}

const ben: Order = {
  id: "o2", showId: "spring", buyerEmail: "ben@example.com",
  quantity: 2, totalCents: 2550, status: "paid",
};
const startSeats = () => new Map([["A1", "o1"], ["A2", "o2"], ["A3", "o2"]]);

test("a paid order moves to a free seat", async () => {
  const seats = startSeats();
  const tx = fakeTransaction([ben], seats);
  const result = await changeSeat(tx, { orderId: "o2", from: "A2", to: "B1" });
  assert.deepEqual(result, { status: "changed", seat: "B1" });
  assert.deepEqual([...seats], [["A1", "o1"], ["A3", "o2"], ["B1", "o2"]]);
});

test("a taken seat leaves the order with its old seat", async () => {
  const seats = startSeats();
  const tx = fakeTransaction([ben], seats);
  const change = changeSeat(tx, { orderId: "o2", from: "A2", to: "A1" });
  await assert.rejects(change, /seat A1 is taken/);
  assert.deepEqual(seats, startSeats());
});

test("only a paid order can change seats", async () => {
  const pending: Order = { ...ben, status: "pending" };
  const seats = startSeats();
  const tx = fakeTransaction([pending], seats);
  const result = await changeSeat(tx, { orderId: "o2", from: "A2", to: "B1" });
  assert.deepEqual(result, { status: "refused", reason: "only a paid order can change seats" });
  assert.deepEqual(seats, startSeats());
});

test("an order cannot move a seat it does not hold", async () => {
  const seats = startSeats();
  const tx = fakeTransaction([ben], seats);
  const result = await changeSeat(tx, { orderId: "o2", from: "A1", to: "C1" });
  assert.deepEqual(result, { status: "refused", reason: "order o2 does not hold seat A1" });
  assert.deepEqual(seats, startSeats());
});

Promise<never> is the type of a promise that never resolves with a value, so unused fits any method that returns a promise. Run the test with npx tsx --test seat-change.test.ts, and check the types with npx tsc --noEmit.

Pause and predict: which writes must succeed or fail together? Which repository needs a new method, and what should that method tell its caller?

Hint 1

Freeing the old seat and taking the new one must happen together, so they go in one withTransaction call. The order check reads through tx.orders.findById inside the same transaction.

Hint 2

SeatRepository needs release(showId, seat, orderId): Promise<boolean>. It answers true when it freed a seat that the order held, and false otherwise. In SQLite, the result of statement.run(...) has a changes field, the number of rows the statement changed.

Hint 3

After you add release, tsc reports an error in place-order.test.ts, because its fake seat repository has no release. Add one that returns false, because placeOrder never frees a seat.

Then write changeSeat(withTransaction, { orderId, from, to }), which checks the status, calls release, then calls reserve. Return a refusal instead of throwing for the two rule failures. But let a taken seat throw, so the transaction rolls back.

Solution

In stores.ts, the seat repository gets release (an excerpt of the changed parts):

export interface SeatRepository {
  reserve(showId: string, seat: string, orderId: string): Promise<void>;
  // NEW: frees a seat if this order holds it; answers false otherwise
  release(showId: string, seat: string, orderId: string): Promise<boolean>;
}

// The seats table has PRIMARY KEY (show_id, seat), so a taken seat throws
export function createSqliteSeatRepository(db: DatabaseSync): SeatRepository {
  const insert = db.prepare("INSERT INTO seats VALUES (?, ?, ?)");
  const remove = db.prepare(
    "DELETE FROM seats WHERE show_id = ? AND seat = ? AND order_id = ?",
  );
  return {
    async reserve(showId, seat, orderId) {
      insert.run(showId, seat, orderId);
    },
    async release(showId, seat, orderId) {
      return remove.run(showId, seat, orderId).changes === 1;
    },
  };
}

In place-order.test.ts, the fake seat repository gets one line (an excerpt):

        async release() { return false; }, // NEW: placeOrder never frees a seat

change-seat.ts:

import type { WithTransaction } from "./transaction.ts";

export type SeatChange = { orderId: string; from: string; to: string };
export type SeatChangeResult =
  | { status: "changed"; seat: string }
  | { status: "refused"; reason: string };

// Free the old seat and take the new one: both happen, or neither does
export async function changeSeat(
  withTransaction: WithTransaction,
  change: SeatChange,
): Promise<SeatChangeResult> {
  const { orderId, from, to } = change;
  return withTransaction(async (tx) => {
    const order = await tx.orders.findById(orderId);
    if (order?.status !== "paid") {
      return { status: "refused", reason: "only a paid order can change seats" };
    }
    if (!(await tx.seats.release(order.showId, from, orderId))) {
      const reason = `order ${orderId} does not hold seat ${from}`;
      return { status: "refused", reason };
    }
    await tx.seats.reserve(order.showId, to, orderId);
    return { status: "changed", seat: to };
  });
}

order?.status is undefined when the order doesn’t exist, so a missing order is refused too. After that check, TypeScript knows that order is defined.

seat-change.ts:

import express from "express";
import { changeSeat } from "./change-seat.ts";
import { openDb } from "./db.ts";
import { createWithTransaction } from "./transaction.ts";

const db = openDb();
const withTransaction = createWithTransaction(db);
await withTransaction(async (tx) => {
  await tx.orders.save({
    id: "o2", showId: "spring", buyerEmail: "ben@example.com",
    quantity: 2, totalCents: 2550, status: "paid",
  });
  for (const [seat, orderId] of [["A1", "o1"], ["A2", "o2"], ["A3", "o2"]]) {
    await tx.seats.reserve("spring", seat, orderId);
  }
});

const app = express();
app.use(express.json());

app.post("/orders/:id/seats", async (req, res) => {
  const body: unknown = req.body;
  if (
    typeof body !== "object" || body === null ||
    !("from" in body) || typeof body.from !== "string" ||
    !("to" in body) || typeof body.to !== "string"
  ) {
    res.status(400).json({ error: "bad input" });
    return;
  }
  const change = { orderId: req.params.id, from: body.from, to: body.to };
  const result = await changeSeat(withTransaction, change);
  if (result.status === "refused") res.status(409).json({ error: result.reason });
  else res.json({ orderId: req.params.id, seat: result.seat });
});

app.listen(3000, () => console.log("TinyTickets listening on port 3000"));

The test output:

✔ a paid order moves to a free seat (0.821333ms)
✔ a taken seat leaves the order with its old seat (0.288167ms)
✔ only a paid order can change seats (0.089083ms)
✔ an order cannot move a seat it does not hold (0.54475ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0

With the same three curl requests, the server answers {"orderId":"o2","seat":"B1"}, then a 500 error for the taken seat A1, then {"error":"order o2 does not hold seat A1"} with status 409. Ben ends with A3 and B1, and Ana keeps A1.

This solution leaves two things as they were. A taken seat still answers with a 500 error, because telling “seat taken” apart from other database errors means checking the SQLite error code. And the route still checks the body by hand, as Module 1 did.

One behavior did change. The show id now comes from the order, where the old code wrote 'spring' into the SQL. That fixes a bug for other shows, but mention the change in the pull request.

Which pattern, if any?

Scenario 1: Leo’s nightly sales report

Leo gets a short report every night. Here is the script, sales-report.ts:

import { openDb } from "./db.ts";

const db = openDb();
db.exec(`INSERT INTO orders VALUES
  ('o1', 'spring', 'ana@example.com', 2, 2550, 'paid'),
  ('o2', 'spring', 'ben@example.com', 4, 4800, 'paid'),
  ('o3', 'summer', 'chi@example.com', 2, 3150, 'paid'),
  ('o4', 'summer', 'ben@example.com', 1, 1650, 'cancelled')`);

// Leo's nightly report: one read-only query, used in this one script
const rows = db.prepare(`
  SELECT show_id, SUM(quantity) AS tickets FROM orders
  WHERE status = 'paid' GROUP BY show_id ORDER BY show_id`).all();
for (const row of rows) console.log(`${String(row.show_id)}: ${Number(row.tickets)} tickets`);

Output:

spring: 6 tickets
summer: 2 tickets

The rows at the top stand in for the real database. The new requirement: Leo also wants the money taken per show. A teammate suggests a ReportRepository interface, a SQLite implementation and a fake, “to be consistent”. What do you do?

Hint

Count the callers of this query, the rules in it that need a test, and the writes. Then look at Figure 8.

A strong answer

No pattern. Add SUM(total_cents) AS cents to the query and print it. The script has one read-only query, one caller and no business rule beyond the SQL.

The SQL is the clearest way to say what the report computes, and a repository would only move it into another file. If you want a test, run the script’s query against openDb() with a few rows, as transaction.test.ts did. Move the query behind a repository later, if a route or a second report needs the same numbers.

Scenario 2: give your tickets to a friend

Buyers can give their order to a friend. Here is transfer-order.ts:

import type { OrderRepository } from "./types.ts";

// Ana gives her tickets to a friend: the order gets the friend's email
export async function transferOrder(
  orders: OrderRepository,
  orderId: string,
  toEmail: string,
): Promise<void> {
  const order = await orders.findById(orderId);
  if (order?.status !== "paid") throw new Error(`order ${orderId} cannot be transferred`);
  await orders.save({ ...order, buyerEmail: toEmail });
}

The new requirement: Leo’s accountant wants a row in a new transfers table for every transfer, with the order id, the old email and the new email. A transfer without its row, or a row without a transfer, must never happen. What do you change?

Hint

How many rows does one transfer write now? What must happen to the first write if the second one fails?

A strong answer

Unit of Work. A transfer now writes two rows that must agree, so both writes go inside one transaction. Add a small TransferRepository with add(transfer), and put it in Repositories as transfers. Then let transferOrder take withTransaction (an excerpt):

export async function transferOrder(
  withTransaction: WithTransaction,
  orderId: string,
  toEmail: string,
): Promise<void> {
  await withTransaction(async (tx) => {
    const order = await tx.orders.findById(orderId);
    if (order?.status !== "paid") throw new Error(`order ${orderId} cannot be transferred`);
    await tx.orders.save({ ...order, buyerEmail: toEmail });
    await tx.transfers.add({ orderId, fromEmail: order.buyerEmail, toEmail });
  });
}

Read the order inside the transaction, so the old email in the audit row is the one you replaced. The repository already existed, so no new pattern is needed for the storage. The cost is that every Repositories fake in your tests needs a transfers field.

Get feedback on your answer

Copy this prompt into an AI assistant, with your answer and the scenario’s code:

I am learning design patterns in TypeScript and Node.js. Here is a scenario
from a course module, the code, and my answer. Review my answer.
1. Did I pick the right pattern, or correctly decide that none is needed?
   Say why in two or three sentences.
2. Name one signal in the code that I missed, if any.
3. Name one cost of my choice that I did not mention.
Do not rewrite my code unless it is wrong. Keep the review under 200 words.

Scenario and code:
<paste here>

My answer:
<paste here>

Going deeper

You can skip this section. It covers details the main path left out.

node:sqlite across Node.js versions

node:sqlite needs no command-line flag since Node.js 22.13 and 23.4. The Node.js docs mark it “Stability: 1.2 – Release candidate”, which means the API is close to final but can still change.

This module uses DatabaseSync, the class name in Node.js 24 and in @types/node. Node.js 26.11 renamed the class Database, and DatabaseSync stays as an alias that the docs mark deprecated (DEP0210). The code runs on both.

When a repository call throws

If a repository call throws inside a route, Express 5 catches the rejected promise and answers with a 500 error, as its error-handling guide says. That’s why the routes in app.ts have no try.

A repository as a class

The fix used a factory function that returns an object, with the prepared statements kept in a closure. You can also write the repository as a class, SqliteOrderRepository, that implements OrderRepository and keeps the prepared statements in private fields. Then one line of main.ts changes: const orders = new SqliteOrderRepository(openDb());.

You meet the class form in TypeORM projects, where the framework creates each repository. With no framework, the function form is shorter and does the same job. So pick the form your codebase already uses.

Fowler’s Unit of Work as a class

Fowler’s catalogue page describes a class that tracks the changes itself. You register each new or changed object, and commit() writes them all in one transaction.

A checkout version of that class has registerOrder, registerPayment and registerSeat, which only add to lists in memory. Then commit() runs BEGIN, writes every list through the repositories, and runs COMMIT, or ROLLBACK if a write throws. The class keeps state, so you create a new one for each request, or the lists would mix two buyers’ changes.

When you write the code yourself, prefer the function form, because it’s shorter and the database already tracks what changed. You meet the class form inside ORMs that track your objects for you. There you load objects, change them, and call one method that writes all the changes.

Transactions on a database server

Inside a transaction, the writes reach the database before COMMIT, but other connections can’t see them yet. ROLLBACK removes them.

With PostgreSQL, a driver pool gives each transaction its own connection, so a second request doesn’t land inside yours. But every statement of one transaction must use the same client, as the node-postgres docs warn.

Repository and Unit of Work in libraries

  • TypeORM. Its Repository object gives you find, findOneBy, save and more for one entity class, which is one table.
  • Prisma. Prisma is an ORM that generates a typed client from a schema file. In Prisma ORM 7, an interactive transaction is prisma.$transaction(async (tx) => { ... }), the same callback shape as withTransaction. If the callback throws, Prisma rolls back the whole transaction.
  • MikroORM. A TypeScript ORM whose docs describe its Unit of Work directly. It tracks the objects you load and persist, and em.flush() writes all the changes inside one transaction. That’s Fowler’s class form, done by a library.

When one database isn’t enough

A saga is a series of steps across several services, each with its own undo step. You use one when a single database transaction can’t cover the work, such as the charge at the payment service. This course doesn’t teach it.

Cheat sheet

Pattern The problem it solves The signal in your code
Repository SQL and column names spread through handlers; rules need a database to test The same SELECT in two handlers; row.some_column in a route
Unit of Work A failure in the middle leaves half-written data Two or more await ...save(...) calls in a row with no transaction
Data Mapper Objects and tables have different shapes Snake-case column names next to camelCase fields
Active Record Simple screens that map one object to one table order.save() on the object itself
No pattern One query in one place A report script or admin task with no rule to test
  • Repository: one object behind an interface holds the SQL for one kind of data, so a rule runs in a test against a plain-object fake.
  • Unit of Work: withTransaction runs BEGIN, then the work, then COMMIT. If the work throws, it runs ROLLBACK and rethrows.
  • Its limit: a transaction covers one database, so it can’t undo the charge at the payment service. Keep slow awaits out of the callback.
  • Data Mapper and Active Record: a mapper like toOrder moves plain objects to and from rows, and an Active Record object saves itself.
  • No pattern: one query in one place, with no rule to test, stays a plain function with the SQL.

Next, Module 8 turns to the nightly show import: a large CSV file of shows that must be read and written piece by piece, with streams and pipelines.

Sources