On Monday, Omar pushed a test for the hold. It checked that a buyer who asks for more seats than are left is told how many are left. It needed PostgreSQL running in Docker, and it took ten seconds.
“I skip that one,” Nina said. “My container is down most days.”
“The rule is a few lines of TypeScript,” Omar said. “Why does it need a database?”
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
No change broke the hold that week, so the skipped test cost nothing yet. But a test that runs only where a container is up protects the rule only on those laptops.
This module moves PostgreSQL and Express to the edge of Sales. The Sale and its rules stay in domain/, a new application/ folder runs each command, and the database sits behind an interface that the domain owns. At the end, Omar’s test runs in milliseconds with no database, and a test fails when the domain imports pg.
After this module, you can:
- state the dependency rule for one context, and turn it into a test that names every import that breaks it
- declare a port as a TypeScript interface that the domain owns, and write a PostgreSQL adapter that
tscchecks against it - write one repository per aggregate that loads and saves a whole
Sale, and say whatpghands you forbigint,numericanddatecolumns - write an application service that owns the transaction and the retry and holds no business rule, and tell it apart from a domain service
- test a command in milliseconds with an in-memory adapter, and say what that fake cannot prove
Where the code stands
Module 7 put the seat rule in the Sale aggregate, which imports nothing outside domain/. Loading and saving a sale are two functions in db/sales.ts, and the commands in services/ open the transaction through changeSale and write the order rows themselves. Figure 1 is the code figure from Module 7.
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Shows}, {Sales}, {Payouts} ..> money/ the shared kernel (#money)
Inside {Sales}: routes/, services/ ..> db/ ..> domain/
domain/ the Sale aggregate: root Sale, its Order
entities; it imports nothing outside domain/
db/sales.ts changeSale, saveSale: one sale per
transaction, saved with its version;
..> {Shows} for the number of seats, by show ID
routes/, services/, jobs/ ..> acl/ ACL ..> [Payment provider]
Only acl/ knows the provider's webhook body.
platform/ the pool, the job queue, settings, page layout, login, email,
the payment provider's client, the organizer dashboard.
Every context ..> platform/. platform/ ..> money/.
app.ts and worker.ts ..> each #.
Figure 1: the contexts as Module 7 left them; services/ reaches the Sale only through db/.
A test for one rule that needs a database
Omar’s test is about the hold command. Module 7 already tests the seat count in Sale with plain functions. Omar wants the command around it: what the buyer is told, and that nothing is saved. That code is holdSeats in src/sales/services/holds.ts. Save his test as src/sales/services/holds.test.ts:
import assert from "node:assert/strict";
import { test } from "node:test";
import { parseCents } from "#money";
import type { Show } from "#shows";
import { holdSeats } from "./holds.ts";
const show: Show = {
id: 1, organizer_id: 1, name: "Test Show", show_date: "2027-03-14", doors_open: "19:00",
place: "Test Club", seats: 2, price_cents: parseCents(1200),
};
const ana = { name: "Ana", email: "ana@tinytickets.example" };
test("a buyer who asks for more seats than are left is told how many are left", async () => {
const hold = await holdSeats(show, ana, [{ kind: "standard", quantity: 3 }]);
assert.deepEqual(hold, { result: "sold out", seatsLeft: 2 });
});
The test builds a show with two seats and asks for three. It imports no pool and writes no SQL.
Pause and predict: with the container running, what does the test print, and how long does the file take?
Run it with the test database’s settings:
node --env-file=.env.test --test src/sales/services/holds.test.ts
What you should see (an excerpt from one run; your numbers will differ):
✖ a buyer who asks for more seats than are left is told how many are left (38.492756ms)
ℹ tests 1
ℹ suites 0
ℹ pass 0
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 10298.897983
...
{
result: 'sold out',
+ seatsLeft: 0
- seatsLeft: 2
}
Two things went wrong. First, the answer came from the database, not from the test. holdSeats takes the show, but changeSale asks findShow for show 1 again and uses the seats it finds there. In tinytickets_test, show 1 is the one app.test.ts fills, so the answer depends on what the last npm test left behind.
Second, the test took 38 ms and the file took 10.3 seconds. The process waited after the test, because the pool still held a connection. app.test.ts ends the pool in an after hook. With after(() => pool.end()) added to Omar’s file, the same file took 0.36 seconds in another run.
On a laptop where the container is not running, as on Nina’s most days, the same command prints this (an excerpt):
✖ a buyer who asks for more seats than are left is told how many are left (12.915341ms)
AggregateError [ECONNREFUSED]:
...
Error: connect ECONNREFUSED ::1:5546
...
Error: connect ECONNREFUSED 127.0.0.1:5546
If you stop your container to try it, start it again with the commands in README.md before Step 1, because --rm deletes its data. In the full output, the stack trace runs through findShow, changeSale and holdSeats, the path in Figure 2.
holds.test.ts --> holdSeats services/holds.ts
--> changeSale db/sales.ts
--> findShow #shows --> pool --> [[PostgreSQL]] X
--> pool.connect, BEGIN, loadSale
--> Sale.hold domain/sale.ts: the rule, no database
--> createPayment #platform --> [Payment provider]
Figure 2: the rule is in Sale.hold, but the test reaches it only through changeSale, which needs a connection first.
No line of the rule needs PostgreSQL. The seat count is in Sale.hold, and the price is in pricing.ts. But holdSeats imports changeSale, changeSale imports the pool, and the pool needs a server. A test of the command gets all of it.
npm test does not help on Nina’s laptop either. It runs migrate.ts first, so without the container it stops at the first connection, before any test, even the ones in domain/. Delete Omar’s file for now; Step 6 brings his test back without the database.
rm src/sales/services/holds.test.ts
Rules in the middle, technology at the edge
Imports point inward
The dependency rule says that code may import only code closer to the business rules than itself, never code further out. Robert C. Martin states it in “The Clean Architecture” (2012):
“source code dependencies can only point inwards” (Martin, 2012)
For one context of TinyTickets, “inward” means three rings. domain/ holds the Sale, the Order and the price rule. application/ holds one function per command. Everything that knows a technology sits outside: routes/ knows Express, db/ knows pg, jobs/ runs in the worker, and one file connects them. Figure 3 shows the imports this module ends with.
the edge routes/ ..> wiring.ts, domain/, db/, pages/, acl/
wiring.ts ..> application/, db/
db/ ..> application/, domain/, {Shows}
jobs/ ..> application/, domain/, db/
acl/ ..> application/
the middle application/ ..> domain/ one function per command
the center domain/ ..> #money only Sale, Order, pricing,
the port SaleRepository
Figure 3: the imports inside Sales at the end of this module; every arrow points toward domain/, and none leaves domain/ or application/ for the edge.
Evans asks for the same thing in the Domain-Driven Design Reference (2015, p. 10, “Layered Architecture”). He wants the domain model isolated from infrastructure, from the user interface, and even from application logic that is not business logic. He adds that another shape, the one the next section describes, may serve that goal as well as layers, or better.
tsc checks types, not which folder imports which. So the rule needs a check of its own, as the boundary between contexts did in Module 3. Step 2 writes it.
Ports belong to the inside, adapters to the outside
The rule creates a problem at once. The command must save a sale, and saving means pg. Alistair Cockburn’s “Hexagonal Architecture” (2005) answers it. His goal is an application that users, programs and automated tests can all drive, and that runs and is tested apart from its databases and devices.
A port is an interface that the application declares, in its own words, for one kind of exchange with the outside. Cockburn calls it “a purposeful conversation”. An adapter is code that connects one technology to a port: it implements the port with that technology, or it calls the application through it.
So the port SaleRepository lives in domain/, and the PostgreSQL adapter in db/ imports it and implements it. At run time, control flows outward: the command calls save, and save runs SQL. In the source, the import points inward. Martin’s essay names the Dependency Inversion Principle as the tool for exactly this split.
In TypeScript, a port is an interface or a function type. Both are erased at run time, so a file that imports a port imports it with import type. With verbatimModuleSyntax on, as in TinyTickets, tsc refuses a plain import of a type; Step 4 shows the error.
A port costs a file and a name, and “go to definition” on sales.save lands on the interface, not on the SQL. Design Patterns in Plain Words lists the same cost for a repository in Module 7.
Adapters that drive, and adapters that are driven
Cockburn names two sides. A driving adapter calls into the application: an Express route, a test, a script. A driven adapter is called by the application: the database, the payment provider, the email service. He calls the shape hexagonal architecture, or ports and adapters, and says the six sides mean nothing.
His point is that an application has these two kinds of boundary, not a top and a bottom. A test is a driving adapter like a route, and an in-memory store is a driven adapter like PostgreSQL. Figure 4 shows both sides for Sales.
Driving adapters call in:
routes/holds.ts --> salesService: holdSeats
routes/webhooks.ts --> salesService: markOrderPaid, cancelOrder
sales.test.ts --> salesService: all three
The application declares the ports it needs:
SaleRepository in domain/
WithTransaction in application/
startPayment, now in application/ (functions in SalesDeps)
Driven adapters fill them:
db/sale-repository.ts ..> SaleRepository --> [[PostgreSQL]]
db/transaction.ts ..> WithTransaction --> [[PostgreSQL]]
application/in-memory.ts ..> WithTransaction arrays and maps, for tests
wiring.ts fills startPayment --> [Payment provider]
Figure 4: two kinds of adapter around one application; the PostgreSQL adapters and the in-memory adapter fill the same ports.
One repository per aggregate
Design Patterns Module 7 taught the Repository pattern: an interface with findById and save that hides how orders are stored. It had one repository per kind of record. Domain-Driven Design changes the unit.
A repository, in DDD, gives the code a collection of every root of one aggregate type, and it hands out and takes back whole aggregates. Evans (Reference, p. 17) adds three limits. A repository selects aggregates by criteria a domain expert would name. It exists only for aggregate roots that need to be found directly. And it returns aggregates fully built, never a part from inside one. This is not a Git repository; the word is the same.
Evans names the problem the limits solve. When any code can query any table, it reaches objects inside an aggregate without the root, and the rules drift into queries. Module 7 still allowed it. A service could call saveOrderState on any order it had read.
TinyTickets gets one repository, for the Sale. There is no OrderRepository, because an order lives inside a sale and changes only through it. The port has three methods, in Leo’s words: the sale of a show, the sale that holds an order, and save. The version check from Module 7 moves into save, so no command can forget it.
Vernon shows the same shape in “Effective Aggregate Design, Part II” (2011, p. 8): one repository per aggregate type, called from the application service. He also allows an exception in Part III (p. 14). A repository method may return a sum computed in SQL when loading every object would be wasteful.
Mapping rows to objects
The adapter turns rows into a Sale and a Sale back into rows. Design Patterns Module 7 called such code a data mapper. Two things make it harder than renaming columns.
First, the Order has a private constructor (Module 6), so the mapper cannot write new Order(...). It uses Order.restore, the factory for an order that already exists, which skips the rule that a new order starts held.
Second, a row’s values arrive in the types pg chose. To see them, save this as try-types.ts in the project folder:
import pg from "pg";
const client = new pg.Client();
await client.connect();
const result = await client.query(
`SELECT 7::integer AS integer, 9007199254740993::bigint AS bigint, 12.50::numeric AS numeric,
'2027-03-14'::date AS date, '2027-03-14 19:00:00+00'::timestamptz AS timestamptz,
'[{"kind": "standard", "quantity": 2}]'::jsonb AS jsonb`,
);
for (const [column, value] of Object.entries(result.rows[0])) {
console.log(column.padEnd(12), (typeof value).padEnd(7), JSON.stringify(value));
}
await client.end();
Pause and predict: which of the six values arrive as strings?
node --env-file=.env.test try-types.ts
What you should see (one run, in a time zone five hours behind UTC; your date line depends on yours):
integer number 7
bigint string "9007199254740993"
numeric string "12.50"
date object "2027-03-14T05:00:00.000Z"
timestamptz object "2027-03-14T19:00:00.000Z"
jsonb object [{"kind":"standard","quantity":2}]
bigint and numeric arrive as strings, because a JavaScript number cannot hold every value of either. The date arrives as a Date at midnight in the Node process’s own time zone. The node-postgres docs on types say the driver reads date and timestamp in local time and parses json and jsonb. A type it has no parser for comes back as a string. Delete the file.
rm try-types.ts
The columns behind a Sale are integer, text, jsonb and timestamptz, so the mapper can copy them. The traps are elsewhere in TinyTickets. Shows reads show_date::text for the reason above, and the dashboard’s counts arrive as strings typed number (Module 10 fixes them). A mapper is the one place to parse such a value, so that no string reaches the domain typed as a number.
An application service runs one command
The command still needs a home. It loads the sale, calls the root, saves it, and decides where the transaction starts and ends.
An application service is the code for one command: it loads aggregates through repositories, calls one method on one of them, saves, and owns the transaction. It holds no business rule. Martin Fowler’s “AnemicDomainModel” (2003) quotes Evans’ description of this layer: “This layer is kept thin.” Vernon (Part I, p. 3, and Part II, p. 8) shows the same shape: one transaction, aggregates loaded through repositories, one command method called.
Fowler’s own catalog has a Service Layer that sets the application’s boundary, controls transactions and coordinates the response. The application service fills that role. The DDD version adds one restriction, that the rules stay in the aggregates.
For TinyTickets, salesService(deps) returns holdSeats, markOrderPaid and cancelOrder. It receives its ports as a deps object, the Dependency Injection style of Design Patterns Module 6. The retry on a version conflict moves here from db/, because running the command again is a decision about the command. The transaction arrives as WithTransaction, the Unit of Work shape from Design Patterns Module 7.
One pg rule shapes the adapter. The node-postgres docs on transactions say “You must use the same client instance for all statements within a transaction.” So the PostgreSQL adapter builds its repository on the transaction’s client. That’s also why findShow gains a client parameter in Step 4. Inside the transaction, it would otherwise take a second connection from the pool, the trap Module 7 met under load.
The composition root is the one file that creates the real adapters and hands them in (Design Patterns Module 6). For Sales it is src/sales/wiring.ts.
A domain service holds a rule that belongs to no one object
The price rule needs a home too. Students pay 20% less, a VIP ticket costs $5 more, and an order of fewer than four tickets pays a $1.50 booking fee. It needs the show’s price and the order’s lines, and it keeps no state.
Evans (Reference, p. 14) describes the case:
“Sometimes, it just isn’t a thing.” (Evans, Reference, p. 14)
A domain service is an operation of the domain that is not the natural job of one entity or value object. It is named in the ubiquitous language, and it keeps no state of its own. pricing.ts already is one. It sits in services/ with the commands, which mixes two kinds of service, so Step 1 moves it into domain/. The Sale calls it when it prices a hold and when it issues tickets.
| Application service | Domain service | |
|---|---|---|
| Folder | application/ |
domain/ |
| Holds a business rule | no | yes |
| Input and output | through ports: repositories, the transaction, the provider | none of its own |
| Knows transactions | yes, it owns them | no |
| In TinyTickets | salesService: holdSeats, markOrderPaid, cancelOrder |
pricing.ts: orderTotalCents, ticketPriceCents |
Figure 5: the two kinds of service; only the domain service holds a rule.
Rule: a rule that needs no input or output lives in
domain/, and a command that needs input or output reaches it through ports.
Move PostgreSQL to the edge, step by step
Each step says why, what to do, the code, and what you should see. Work in the project folder Module 7 left. The finished code is in the code/module-08/ folder of the course repository. If you kept the exercise from Module 4, your test counts are one higher.
Step 1: Move the price rule into domain/, and services/ to application/
Why: the price rule is a domain service, so it belongs inside. What is left in services/ are the commands, which are application services, so the folder takes their name. A commit that only moves files and fixes their imports lets Git follow each file (Module 1).
What to do: move the files, and type-check.
git mv src/sales/services/pricing.ts src/sales/domain/pricing.ts
git mv src/sales/services/pricing.test.ts src/sales/domain/pricing.test.ts
git mv src/sales/services src/sales/application
npm run check
What you should see:
> check
> tsc --noEmit
src/sales/acl/payment-provider.ts(2,30): error TS2307: Cannot find module '../services/orders.ts' or its corresponding type declarations.
src/sales/application/holds.ts(6,33): error TS2307: Cannot find module './pricing.ts' or its corresponding type declarations.
src/sales/application/holds.ts(7,32): error TS2307: Cannot find module './pricing.ts' or its corresponding type declarations.
src/sales/application/orders.ts(8,34): error TS2307: Cannot find module './pricing.ts' or its corresponding type declarations.
src/sales/db/orders.ts(3,32): error TS2307: Cannot find module '../services/pricing.ts' or its corresponding type declarations.
src/sales/jobs/send-confirmation.ts(5,30): error TS2307: Cannot find module '../services/orders.ts' or its corresponding type declarations.
src/sales/jobs/send-confirmation.ts(6,51): error TS2307: Cannot find module '../services/pricing.ts' or its corresponding type declarations.
src/sales/routes/holds.ts(5,29): error TS2307: Cannot find module '../services/pricing.ts' or its corresponding type declarations.
src/sales/routes/holds.ts(6,32): error TS2307: Cannot find module '../services/pricing.ts' or its corresponding type declarations.
src/sales/routes/holds.ts(8,27): error TS2307: Cannot find module '../services/holds.ts' or its corresponding type declarations.
src/sales/routes/webhooks.ts(5,44): error TS2307: Cannot find module '../services/orders.ts' or its corresponding type declarations.
Three replacements fix all eleven. Outside application/, ../services/pricing.ts becomes ../domain/pricing.ts, and any other ../services/ becomes ../application/. Inside application/, ./pricing.ts becomes ../domain/pricing.ts. Make them by hand, or with Perl, which works the same on macOS and Linux:
perl -pi -e 's#"\.\./services/pricing\.ts"#"../domain/pricing.ts"#; s#"\.\./services/#"../application/#' src/sales/acl/payment-provider.ts src/sales/db/orders.ts src/sales/jobs/send-confirmation.ts src/sales/routes/holds.ts src/sales/routes/webhooks.ts
perl -pi -e 's#"\./pricing\.ts"#"../domain/pricing.ts"#' src/sales/application/holds.ts src/sales/application/orders.ts
Run npm run check (no errors) and npm test (36 pass), then commit:
git add -A
git commit -m "Move the price rule to domain/, and services/ to application/"
[main edb8031] Move the price rule to domain/, and services/ to application/
9 files changed, 11 insertions(+), 11 deletions(-)
rename src/sales/{services => application}/holds.ts (93%)
rename src/sales/{services => application}/orders.ts (97%)
rename src/sales/{services => domain}/pricing.test.ts (100%)
rename src/sales/{services => domain}/pricing.ts (100%)
The two pricing files moved unchanged (100%). The two command files changed only in their import lines.
Step 2: Write the dependency rule as a test
Why: nothing checks the rule yet. Module 3’s test fails when one context reaches into another; this one fails when the inner folders of a context reach out.
What to do: add this at the end of test/boundaries.test.ts. It reuses src and specifier from the first test (an excerpt):
// The dependency rule inside a context: domain/ imports only domain/, and
// application/ only domain/ and application/. Both may use the money kernel
// and node: modules that do no input or output.
const inner: Record<string, string[]> = { domain: ["domain"], application: ["domain", "application"] };
const pure = new Set(["#money", "node:assert/strict", "node:crypto", "node:test"]);
test("domain/ and application/ import nothing from the outside world", () => {
const leaks: string[] = [];
for (const file of readdirSync(src, { recursive: true, encoding: "utf8" })) {
const [context, layer] = file.split(sep);
const allowed = inner[layer!];
if (!file.endsWith(".ts") || allowed === undefined) continue;
for (const [, spec] of readFileSync(join(src, file), "utf8").matchAll(specifier)) {
const [toContext, toLayer] = relative(src, resolve(src, dirname(file), spec)).split(sep);
const inside = spec.startsWith(".") && toContext === context && allowed.includes(toLayer!);
if (!inside && !pure.has(spec)) leaks.push(`${file} -> ${spec}`);
}
}
assert.deepEqual(leaks, []);
});
The test looks at files whose second folder is domain or application. An import passes if it is relative and lands in an allowed folder of the same context, or if it is one of four names in pure. Everything else is a leak: pg, express, #platform, another context’s # entry, or ../db/.
It is an allow-list, not a list of forbidden names. A new package is refused until someone adds it to pure, which is a decision someone has to make on purpose. node:crypto is on the list because the commands make random tokens; it does no input or output.
Run only the boundary tests. They need no database:
node --test test/
What you should see (an excerpt):
✔ a context imports another context only through its # entry (7.416857ms)
✖ domain/ and application/ import nothing from the outside world (3.600703ms)
...
+ [
+ 'sales/application/holds.ts -> ../db/orders.ts',
+ 'sales/application/holds.ts -> ../db/sales.ts',
+ 'sales/application/holds.ts -> #shows',
+ 'sales/application/holds.ts -> #platform',
+ 'sales/application/orders.ts -> #platform',
+ 'sales/application/orders.ts -> ../db/orders.ts',
+ 'sales/application/orders.ts -> ../db/sales.ts',
+ 'sales/application/orders.ts -> #shows',
+ 'sales/application/orders.ts -> ../db/tickets.ts'
+ ]
- []
Nine imports break the rule, all in the two command files, and domain/ has none. Steps 3 to 5 remove them. Module 3 said a lint tool is worth its packages when the rules grow; two rules still fit in one test file. Commit anyway, so each of the next steps is one diff:
git add -A
git commit -m "Test the dependency rule inside a context"
Step 3: Give the Sale everything its repository must save, and write the port
Why: a repository saves whole aggregates. Today the Order holds its token, its seats and its state, and the command writes the buyer, the lines and the total into the row itself. The price also lives outside the Sale, so the command computes the total.
What to do: in src/sales/domain/order.ts, add the order’s details, and let the seats come from the lines (three excerpts; the imports go at the top):
import type { Cents } from "#money";
import type { OrderLine } from "./pricing.ts";
// What the buyer asked for, and its price. It does not change after the hold.
export type OrderDetails = {
readonly buyerName: string;
readonly buyerEmail: string;
readonly lines: OrderLine[];
readonly totalCents: Cents;
};
readonly token: string;
readonly details: OrderDetails;
#state: OrderState;
private constructor(token: string, details: OrderDetails, state: OrderState) {
this.token = token;
this.details = details;
this.#state = state;
}
// A new order starts with a hold of HOLD_MINUTES.
static hold(token: string, details: OrderDetails, now: Date): Order {
return new Order(token, details, { status: "held", holdExpiresAt: new Date(now.getTime() + HOLD_MINUTES * 60_000) });
}
// An order that already exists, read back from storage.
static restore(token: string, details: OrderDetails, state: OrderState): Order {
return new Order(token, details, state);
}
get seats(): number {
return this.details.lines.reduce((sum, line) => sum + line.quantity, 0);
}
seats is now a getter over the lines, so the number of seats and the lines can never disagree. Replace src/sales/domain/sale.ts with this:
import type { Cents } from "#money";
import { Order } from "./order.ts";
import type { FailureOutcome, PaymentOutcome } from "./order.ts";
import { orderTotalCents, ticketPriceCents } from "./pricing.ts";
import type { OrderLine, TicketKind } from "./pricing.ts";
// What code outside the sale may use of one of its orders. It can read the
// order; it changes the order only through the sale.
export type OrderView = Pick<Order, "token" | "seats" | "state" | "details">;
export type Buyer = { readonly name: string; readonly email: string };
export type HoldOutcome =
| { readonly result: "held"; readonly order: OrderView }
| { readonly result: "sold out"; readonly seatsLeft: number };
export type NewTicket = { readonly kind: TicketKind; readonly code: string; readonly priceCents: Cents };
// The sale of one show in Sales (see "Sale" in GLOSSARY.md): its seats, its
// price, and every order for it. The rule it keeps: the orders that take
// seats never take more seats than the show has.
export class Sale {
readonly showId: number;
readonly seats: number;
readonly priceCents: Cents;
readonly version: number;
readonly #orders: Order[];
// The orders this copy of the sale added or changed, so that a repository
// writes only those.
readonly #added: Order[] = [];
readonly #changed = new Set<Order>();
private constructor(showId: number, seats: number, priceCents: Cents, version: number, orders: Order[]) {
this.showId = showId;
this.seats = seats;
this.priceCents = priceCents;
this.version = version;
this.#orders = orders;
}
// A sale read back from storage, with the version it had then.
static restore(showId: number, seats: number, priceCents: Cents, version: number, orders: Order[]): Sale {
return new Sale(showId, seats, priceCents, version, [...orders]);
}
seatsLeft(now: Date): number {
const taken = this.#orders
.filter((order) => order.holdsSeats(now))
.reduce((sum, order) => sum + order.seats, 0);
return this.seats - taken;
}
// A buyer asks for seats. The new order is priced, and held only if the
// seats are free.
hold(token: string, buyer: Buyer, lines: OrderLine[], now: Date): HoldOutcome {
const totalCents = orderTotalCents(this.priceCents, lines);
const order = Order.hold(token, { buyerName: buyer.name, buyerEmail: buyer.email, lines, totalCents }, now);
const seatsLeft = this.seatsLeft(now);
if (order.seats > seatsLeft) {
return { result: "sold out", seatsLeft };
}
this.#orders.push(order);
this.#added.push(order);
return { result: "held", order };
}
// Paying keeps an order's seats after its hold would have run out, so a
// payment changes the sale, and goes through it.
pay(token: string, now: Date): PaymentOutcome {
const order = this.#find(token);
this.#changed.add(order);
return order.pay(now);
}
cancel(token: string, now: Date): FailureOutcome {
const order = this.#find(token);
this.#changed.add(order);
return order.cancel(now);
}
order(token: string): OrderView {
return this.#find(token);
}
// The tickets of a paid order: one per seat, at the price of its kind.
tickets(token: string, newCode: () => string): NewTicket[] {
return this.#find(token).details.lines.flatMap((line) =>
Array.from({ length: line.quantity }, () => ({
kind: line.kind, code: newCode(), priceCents: ticketPriceCents(this.priceCents, line.kind),
})),
);
}
// What a repository must write when it saves this sale.
changes(): { added: OrderView[]; changed: OrderView[] } {
return { added: [...this.#added], changed: [...this.#changed] };
}
#find(token: string): Order {
const order = this.#orders.find((one) => one.token === token);
if (order === undefined) {
throw new Error(`Order ${token} is not in the sale of show ${this.showId}.`);
}
return order;
}
}
Notice four things:
priceCentsjoinsseatsas a value copied from Shows by show ID, as in Module 7. With it,holdprices the order through the domain service, and the command computes nothing.ticketsis the rule “one ticket per seat, at the price of its kind”, which Module 7 kept in the payment command. It takesnewCodeas a function, so the domain makes no random numbers of its own and a test can pass a fixed code.changeslists the orders this copy added and the ones it changed. The repository writes only those, instead of every order of the show.- The
Salestill imports onlydomain/and#money.
Now the port. Save this as src/sales/domain/sale-repository.ts:
import type { Sale } from "./sale.ts";
// The port through which Sales stores its sales (see "Sale" in GLOSSARY.md).
// It hands out whole sales and takes whole sales back. An adapter decides
// where they live: src/sales/db/ for PostgreSQL.
export interface SaleRepository {
// The sale of one show, or undefined when there is no such show.
saleOf(showId: number): Promise<Sale | undefined>;
// The sale that holds an order, or undefined when there is no such order.
saleOfOrder(token: string): Promise<Sale | undefined>;
// Saves the sale with the orders it added or changed. Throws
// SaleChangedError when another copy of the sale was saved after this one
// was loaded.
save(sale: Sale): Promise<void>;
}
export class SaleChangedError extends Error {}
The port speaks the domain’s language: a sale, an order’s token, a show’s ID. It names no table, no client and no SQL. SaleChangedError moves here from db/, because the application service must catch it without importing db/.
The domain tests need new arguments. In src/sales/domain/order.test.ts, add two imports and one value after minutesLater (two excerpts). Then pass twoSeats where each test passed 2: Order.hold("t1", 2, tenOClock) becomes Order.hold("t1", twoSeats, tenOClock), and the same for t2 to t5.
import { parseCents } from "#money";
import { Order } from "./order.ts";
import type { OrderDetails } from "./order.ts";
const twoSeats: OrderDetails = {
buyerName: "Ana", buyerEmail: "ana@tinytickets.example",
lines: [{ kind: "standard", quantity: 2 }], totalCents: parseCents(2550),
};
Replace src/sales/domain/sale.test.ts with this. The first four tests are Module 7’s, rewritten for the new arguments; the last three are new:
import assert from "node:assert/strict";
import { test } from "node:test";
import { parseCents } from "#money";
import { Order } from "./order.ts";
import type { OrderLine } from "./pricing.ts";
import { Sale } from "./sale.ts";
const tenOClock = new Date("2027-03-01T10:00:00Z");
const minutesLater = (minutes: number) => new Date(tenOClock.getTime() + minutes * 60_000);
const twelveDollars = parseCents(1200);
const ana = { name: "Ana", email: "ana@tinytickets.example" };
const standard = (quantity: number): OrderLine[] => [{ kind: "standard", quantity }];
test("a sale holds seats until it has none left", () => {
const sale = Sale.restore(1, 3, twelveDollars, 0, []);
assert.equal(sale.hold("a", ana, standard(2), tenOClock).result, "held");
assert.deepEqual(sale.hold("b", ana, standard(2), tenOClock), { result: "sold out", seatsLeft: 1 });
assert.equal(sale.hold("c", ana, standard(1), tenOClock).result, "held");
assert.equal(sale.seatsLeft(tenOClock), 0);
});
test("a hold that ran out gives its seats to the next buyer", () => {
const sale = Sale.restore(1, 2, twelveDollars, 0, []);
sale.hold("a", ana, standard(2), tenOClock);
assert.equal(sale.hold("b", ana, standard(2), minutesLater(9)).result, "sold out");
assert.equal(sale.hold("c", ana, standard(2), minutesLater(10)).result, "held");
});
test("a paid order keeps its seats after its hold would have run out", () => {
const sale = Sale.restore(1, 2, twelveDollars, 0, []);
sale.hold("a", ana, standard(2), tenOClock);
assert.equal(sale.pay("a", minutesLater(5)), "paid");
assert.equal(sale.hold("b", ana, standard(1), minutesLater(30)).result, "sold out");
});
test("two copies of one sale both give away its last seat", () => {
const first = Sale.restore(1, 1, twelveDollars, 7, []);
const second = Sale.restore(1, 1, twelveDollars, 7, []);
assert.equal(first.hold("a", ana, standard(1), tenOClock).result, "held");
assert.equal(second.hold("b", ana, standard(1), tenOClock).result, "held");
});
test("a hold for one student ticket is priced with the booking fee", () => {
const sale = Sale.restore(1, 2, twelveDollars, 0, []);
assert.equal(sale.hold("a", ana, [{ kind: "student", quantity: 1 }], tenOClock).result, "held");
assert.equal(sale.order("a").details.totalCents, 1110);
});
test("a paid order gets one ticket per seat, at the price of its kind", () => {
const sale = Sale.restore(1, 3, twelveDollars, 0, []);
sale.hold("a", ana, [{ kind: "standard", quantity: 2 }, { kind: "vip", quantity: 1 }], tenOClock);
sale.pay("a", minutesLater(1));
const tickets = sale.tickets("a", () => "CODE");
assert.deepEqual(tickets.map((ticket) => [ticket.kind, ticket.priceCents]), [["standard", 1200], ["standard", 1200], ["vip", 1700]]);
});
test("a sale lists the orders it added and the ones it changed", () => {
const details = { buyerName: "Ana", buyerEmail: ana.email, lines: standard(2), totalCents: parseCents(2550) };
const held = Order.restore("a", details, { status: "held", holdExpiresAt: minutesLater(10) });
const sale = Sale.restore(1, 4, twelveDollars, 3, [held]);
sale.cancel("a", minutesLater(1));
sale.hold("b", ana, standard(2), minutesLater(2));
assert.deepEqual(sale.changes().added.map((order) => order.token), ["b"]);
assert.deepEqual(sale.changes().changed.map((order) => order.token), ["a"]);
});
Run the domain tests alone, then the type check:
node --test src/sales/domain/
npm run check
What you should see (two excerpts):
ℹ tests 15
ℹ suites 0
ℹ pass 15
ℹ fail 0
src/sales/application/holds.ts(23,26): error TS2554: Expected 4 arguments, but got 3.
src/sales/db/orders.ts(21,39): error TS2345: Argument of type 'number' is not assignable to parameter of type 'OrderDetails'.
src/sales/db/orders.ts(23,39): error TS2345: Argument of type 'number' is not assignable to parameter of type 'OrderDetails'.
src/sales/db/orders.ts(25,39): error TS2345: Argument of type 'number' is not assignable to parameter of type 'OrderDetails'.
src/sales/db/sales.ts(17,15): error TS2554: Expected 5 arguments, but got 4.
The 15 domain tests (5 order, 3 pricing, 7 sale) pass, and they never touched a database. The five errors are the old callers in db/ and application/, which Steps 4 and 5 replace. Commit:
git add -A
git commit -m "Give the sale everything it needs to be saved whole, and add its port"
Step 4: Store the sale through a PostgreSQL adapter
Why: the port needs an adapter that the web app can use. It replaces loadSale and saveSale, and it runs every query on one transaction’s client.
What to do: first, let findShow take a client. In src/shows/db/shows.ts, add an import, and change the function’s first lines (two excerpts):
import type pg from "pg";
// A caller inside a transaction passes its client, so that the query does not
// wait for a second connection from the pool.
export async function findShow(id: number, client: pg.Pool | pg.PoolClient = pool): Promise<Show | undefined> {
const result = await client.query<Show>(
The default keeps every other caller as it is. The cost is that Shows’ public entry now names a pg type. Shows has no domain/ folder yet, and its code is all in db/, so the dependency rule has nothing to check there.
In src/sales/db/orders.ts, the mapper fills the order’s details, and the insert reads them from the order (an excerpt):
// Maps a row to an Order: snake_case columns to the entity's names. The
// CHECK orders_one_state (migration 018) makes paid_at and cancelled_at
// match the status, so the "!" below cannot be wrong.
export function orderFromRow(row: OrderRow): Order {
const details = {
buyerName: row.buyer_name, buyerEmail: row.buyer_email, lines: row.lines, totalCents: row.total_cents,
};
switch (row.status) {
case "held":
return Order.restore(row.token, details, { status: "held", holdExpiresAt: row.hold_expires_at });
case "paid":
return Order.restore(row.token, details, { status: "paid", paidAt: row.paid_at! });
case "cancelled":
return Order.restore(row.token, details, { status: "cancelled", cancelledAt: row.cancelled_at! });
}
}
// Writes a new order. Only a held order is new.
export async function insertOrder(order: OrderView, showId: number, client: pg.PoolClient): Promise<void> {
const state = order.state;
if (state.status !== "held") {
throw new Error(`Order ${order.token} is ${state.status}; a new order must be held.`);
}
const { buyerName, buyerEmail, lines, totalCents } = order.details;
await client.query(
`INSERT INTO sales.orders (token, show_id, buyer_name, buyer_email, quantity,
lines, total_cents, hold_expires_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
[order.token, showId, buyerName, buyerEmail, order.seats,
JSON.stringify(lines), totalCents, state.holdExpiresAt],
);
}
In the same file, saveOrderState now requires a client, because only the adapter calls it, inside a transaction. savePayment finds the order by its token, which is all the application knows after the commit (two excerpts):
export async function saveOrderState(order: OrderView, client: pg.PoolClient): Promise<void> {
export async function savePayment(token: string, paymentId: string, paymentUrl: string): Promise<void> {
await pool.query(
"UPDATE sales.orders SET payment_id = $1, payment_url = $2 WHERE token = $3",
[paymentId, paymentUrl, token],
);
}
Now the adapter. Save this as src/sales/db/sale-repository.ts:
import type pg from "pg";
import { findShow } from "#shows";
import { Sale } from "../domain/sale.ts";
import { SaleChangedError } from "../domain/sale-repository.ts";
import type { SaleRepository } from "../domain/sale-repository.ts";
import { insertOrder, orderFromRow, saveOrderState } from "./orders.ts";
import type { OrderRow } from "./orders.ts";
// The PostgreSQL adapter for the SaleRepository port. Every query runs on the
// client of one transaction, so it never waits for a second connection.
export function postgresSaleRepository(client: pg.PoolClient): SaleRepository {
async function saleOf(showId: number): Promise<Sale | undefined> {
const show = await findShow(showId, client);
if (show === undefined) {
return undefined;
}
// The first hold of a show adds its row.
await client.query("INSERT INTO sales.sales (show_id) VALUES ($1) ON CONFLICT DO NOTHING", [show.id]);
const sale = await client.query<{ version: number }>(
"SELECT version FROM sales.sales WHERE show_id = $1",
[show.id],
);
const orders = await client.query<OrderRow>("SELECT * FROM sales.orders WHERE show_id = $1", [show.id]);
return Sale.restore(show.id, show.seats, show.price_cents, sale.rows[0]!.version, orders.rows.map(orderFromRow));
}
return {
saleOf,
async saleOfOrder(token) {
const order = await client.query<{ show_id: number }>("SELECT show_id FROM sales.orders WHERE token = $1", [token]);
return order.rows[0] === undefined ? undefined : saleOf(order.rows[0].show_id);
},
// The version first: a command that lost the race fails here, before it
// writes anything else.
async save(sale) {
const result = await client.query(
"UPDATE sales.sales SET version = version + 1 WHERE show_id = $1 AND version = $2",
[sale.showId, sale.version],
);
if (result.rowCount === 0) {
throw new SaleChangedError(`The sale of show ${sale.showId} changed after version ${sale.version}.`);
}
const { added, changed } = sale.changes();
for (const order of added) {
await insertOrder(order, sale.showId, client);
}
for (const order of changed) {
await saveOrderState(order, client);
}
},
};
}
saleOf is Module 7’s loadSale, with the show read on the same client. save is Module 7’s saveSale, followed by the writes the commands used to make themselves. The adapter is a function that returns an object, the function form of Design Patterns Module 7. A class would also work, but TypeScript’s parameter properties are not erasable syntax, so its fields would need to be assigned by hand.
db/sales.ts has nothing left to do. Delete it, and let the hold route take SaleChangedError from the port (an excerpt of src/sales/routes/holds.ts):
git rm src/sales/db/sales.ts
import { SaleChangedError } from "../domain/sale-repository.ts";
Run npm run check.
What you should see:
> check
> tsc --noEmit
src/sales/application/holds.ts(3,38): error TS2307: Cannot find module '../db/sales.ts' or its corresponding type declarations.
src/sales/application/holds.ts(22,49): error TS7006: Parameter 'sale' implicitly has an 'any' type.
src/sales/application/holds.ts(22,55): error TS7006: Parameter 'client' implicitly has an 'any' type.
src/sales/application/holds.ts(28,50): error TS2345: Argument of type '{ showId: number; buyerName: string; buyerEmail: string; lines: OrderLine[]; totalCents: Cents; }' is not assignable to parameter of type 'number'.
src/sales/application/orders.ts(5,38): error TS2307: Cannot find module '../db/sales.ts' or its corresponding type declarations.
src/sales/application/orders.ts(18,56): error TS7006: Parameter 'sale' implicitly has an 'any' type.
src/sales/application/orders.ts(18,62): error TS7006: Parameter 'client' implicitly has an 'any' type.
src/sales/application/orders.ts(52,40): error TS7006: Parameter 'sale' implicitly has an 'any' type.
src/sales/application/orders.ts(52,46): error TS7006: Parameter 'client' implicitly has an 'any' type.
Every error is in application/, which Step 5 rewrites. db/ type-checks against the port.
Now make the adapter drift from its port on purpose. In src/sales/db/sale-repository.ts, change import type { SaleRepository } to import { SaleRepository }, delete the whole save method with its comment, and run npm run check again.
What you should see (the last two lines; the nine errors above come first):
src/sales/db/sale-repository.ts(5,10): error TS1484: 'SaleRepository' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled.
src/sales/db/sale-repository.ts(27,3): error TS2741: Property 'save' is missing in type '{ saleOf: (showId: number) => Promise<Sale | undefined>; saleOfOrder(token: string): Promise<Sale | undefined>; }' but required in type 'SaleRepository'.
The first error says the port does not exist at run time, so the import must say type. The second says the adapter no longer fulfills the port. A cast such as as SaleRepository would silence it, and the web app would throw at the first hold, when it calls save. So the tests against PostgreSQL still matter. Undo both changes, and commit:
git checkout src/sales/db/sale-repository.ts
git add -A
git commit -m "Store the sale through a PostgreSQL repository"
Step 5: Run every command through an application service
Why: application/holds.ts and application/orders.ts still call changeSale, the pool and the provider directly. One file with three application services replaces them, and it reaches the outside only through ports.
What to do: delete the two files, and save this as src/sales/application/sales.ts:
git rm src/sales/application/holds.ts src/sales/application/orders.ts
import { randomBytes } from "node:crypto";
import type { Cents } from "#money";
import type { OrderLine } from "../domain/pricing.ts";
import type { Buyer, NewTicket } from "../domain/sale.ts";
import { SaleChangedError } from "../domain/sale-repository.ts";
import type { SaleRepository } from "../domain/sale-repository.ts";
// A payment in Sales' words (see "Payment" in GLOSSARY.md).
export type Payment = { orderToken: string; paymentId: string; amountCents: Cents };
// What one transaction may write through.
export type SalesTransaction = {
sales: SaleRepository;
issueTickets(orderToken: string, tickets: NewTicket[]): Promise<void>;
};
export type WithTransaction = <T>(work: (tx: SalesTransaction) => Promise<T>) => Promise<T>;
// The ports the application services need. src/sales/wiring.ts fills them
// for the web app; a test fills them with fakes.
export type SalesDeps = {
withTransaction: WithTransaction;
// Asks the payment provider for a payment page for the order, and returns its address.
startPayment(orderToken: string, amountCents: Cents): Promise<string>;
queueConfirmation(payment: Payment): Promise<void>;
now(): Date;
};
export type HoldResult =
| { result: "held"; payUrl: string }
| { result: "sold out"; seatsLeft: number };
const ATTEMPTS = 3;
const newTicketCode = () => randomBytes(4).toString("hex").toUpperCase();
// The application services of Sales, one per command. Each one loads a sale,
// calls one of its methods, and saves it, in one transaction. The rules are
// in the Sale.
export function salesService(deps: SalesDeps) {
// Runs the work in a transaction. When another command saved the same sale
// first, it runs the work again, on fresh data.
async function inTransaction<T>(work: (tx: SalesTransaction) => Promise<T>): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await deps.withTransaction(work);
} catch (error) {
if (!(error instanceof SaleChangedError) || attempt === ATTEMPTS) {
throw error;
}
}
}
}
return {
async holdSeats(showId: number, buyer: Buyer, lines: OrderLine[]): Promise<HoldResult> {
const outcome = await inTransaction(async ({ sales }) => {
const sale = await sales.saleOf(showId);
if (sale === undefined) {
throw new Error(`There is no show ${showId}.`);
}
const outcome = sale.hold(randomBytes(16).toString("hex"), buyer, lines, deps.now());
if (outcome.result === "held") {
await sales.save(sale);
}
return outcome;
});
if (outcome.result === "sold out") {
return outcome;
}
// The payment provider is called after the commit, so no transaction
// stays open while it answers.
const payUrl = await deps.startPayment(outcome.order.token, outcome.order.details.totalCents);
return { result: "held", payUrl };
},
async markOrderPaid(payment: Payment): Promise<void> {
const token = payment.orderToken;
const outcome = await inTransaction(async ({ sales, issueTickets }) => {
const sale = await sales.saleOfOrder(token);
if (sale === undefined) {
return "no such order";
}
const outcome = sale.pay(token, deps.now());
await sales.save(sale);
if (outcome !== "paid") {
return outcome;
}
await deps.queueConfirmation(payment);
await issueTickets(token, sale.tickets(token, newTicketCode));
const totalCents = sale.order(token).details.totalCents;
if (payment.amountCents !== totalCents) {
throw new Error(`Order ${token}: paid ${payment.amountCents} cents, expected ${totalCents}.`);
}
return outcome;
});
if (outcome === "too late") {
console.error(`Order ${token} was cancelled before payment ${payment.paymentId} came. Refund it by hand.`);
}
},
async cancelOrder(payment: Payment): Promise<void> {
await inTransaction(async ({ sales }) => {
const sale = await sales.saleOfOrder(payment.orderToken);
if (sale?.cancel(payment.orderToken, deps.now()) === "cancelled") {
await sales.save(sale);
}
});
},
};
}
Notice three things:
- Each command has the same shape: load one sale, call one method on its root, save. The decisions are in
hold,pay,cancelandtickets. The amount check is the one comparison left here, and Module 9 moves it. - The ports are types:
SaleRepositoryfrom the domain, andWithTransaction,startPayment,queueConfirmationandnowhere. The clock is a port too, so a test can choose the time. markOrderPaidno longer reads the order’s row before the transaction.saleOfOrderfinds the sale inside it, and the order’s lines and total come from theOrder.
The order of the work inside markOrderPaid stays as it was, on purpose. The email job is still queued on its own connection, before the tickets, and the amount check still comes last. Module 9 fixes both.
The tickets need one function in src/sales/db/tickets.ts. Replace insertTicket with this, and add import type { NewTicket } from "../domain/sale.ts"; under the other imports (an excerpt):
// Writes the tickets of a paid order. The show, the order's row and the
// buyer's name come from the order.
export async function issueTickets(client: pg.PoolClient, orderToken: string, tickets: NewTicket[]): Promise<void> {
for (const ticket of tickets) {
await client.query(
`INSERT INTO sales.tickets (show_id, order_id, buyer_name, code, kind, price_cents)
SELECT show_id, id, buyer_name, $2, $3, $4 FROM sales.orders WHERE token = $1`,
[orderToken, ticket.code, ticket.kind, ticket.priceCents],
);
}
}
The transaction is the second driven adapter. Save this as src/sales/db/transaction.ts:
import { pool } from "#platform";
import type { WithTransaction } from "../application/sales.ts";
import { postgresSaleRepository } from "./sale-repository.ts";
import { issueTickets } from "./tickets.ts";
// The PostgreSQL adapter for WithTransaction: one client from the pool, BEGIN,
// the work, COMMIT, and ROLLBACK when the work throws. Every adapter the work
// gets uses that client.
export const withTransaction: WithTransaction = async (work) => {
const client = await pool.connect();
try {
await client.query("BEGIN");
const result = await work({
sales: postgresSaleRepository(client),
issueTickets: (orderToken, tickets) => issueTickets(client, orderToken, tickets),
});
await client.query("COMMIT");
return result;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
};
db/transaction.ts imports a type from application/. That arrow points inward, so the rule allows it. Then the composition root. Save this as src/sales/wiring.ts:
import { createPayment, enqueue } from "#platform";
import { salesService } from "./application/sales.ts";
import { savePayment } from "./db/orders.ts";
import { withTransaction } from "./db/transaction.ts";
// The composition root of Sales: the one file that picks an adapter for each
// port of the application services.
export const sales = salesService({
withTransaction,
async startPayment(orderToken, amountCents) {
const payment = await createPayment(amountCents, orderToken);
await savePayment(orderToken, payment.id, payment.payUrl);
return payment.payUrl;
},
queueConfirmation: (payment) => enqueue("send_confirmation", { payment }),
now: () => new Date(),
});
The routes are driving adapters, and they call the wired service. In src/sales/routes/holds.ts, replace the import of holdSeats and its call (two excerpts):
import { sales } from "../wiring.ts";
hold = await sales.holdSeats(show.id, { name, email }, lines);
In src/sales/routes/webhooks.ts, replace the import from ../application/orders.ts with the same import { sales } from "../wiring.ts";, and call sales.markOrderPaid(news.payment) and sales.cancelOrder(news.payment). Payment lives in the new file, so src/sales/acl/payment-provider.ts and src/sales/jobs/send-confirmation.ts import it from there (an excerpt, the same line in both):
import type { Payment } from "../application/sales.ts";
Run npm run check and npm test.
What you should see: no tsc errors, and all 40 tests pass, the dependency rule among them (an excerpt):
✔ a context imports another context only through its # entry (21.95211ms)
✔ domain/ and application/ import nothing from the outside world (2.954244ms)
ℹ tests 40
ℹ suites 0
ℹ pass 40
ℹ fail 0
The load test from Module 7 still holds the last seat once. findShow now runs on the transaction’s client, so 50 waiting commands do not each wait for a second connection. Commit:
git add -A
git commit -m "Run every command through an application service"
Step 6: Test the commands without a database
Why: this is Omar’s test. The commands now reach the outside only through ports, so a test can fill the ports with plain objects.
What to do: save this second adapter for the same ports as src/sales/application/in-memory.ts:
import type { Cents } from "#money";
import { Order } from "../domain/order.ts";
import type { OrderDetails, OrderState } from "../domain/order.ts";
import { Sale } from "../domain/sale.ts";
import type { NewTicket } from "../domain/sale.ts";
import { SaleChangedError } from "../domain/sale-repository.ts";
import type { WithTransaction } from "./sales.ts";
type StoredOrder = { showId: number; token: string; details: OrderDetails; state: OrderState };
// An adapter for tests: the ports of src/sales/db/, kept in arrays and maps.
// shortcut: no rollback, so a test that needs one runs against PostgreSQL.
export function inMemorySales(shows: { id: number; seats: number; priceCents: Cents }[]) {
const versions = new Map<number, number>();
const orders: StoredOrder[] = [];
const tickets: (NewTicket & { orderToken: string })[] = [];
function saleOf(showId: number): Sale | undefined {
const show = shows.find((one) => one.id === showId);
if (show === undefined) {
return undefined;
}
const own = orders
.filter((order) => order.showId === showId)
.map((order) => Order.restore(order.token, order.details, order.state));
return Sale.restore(show.id, show.seats, show.priceCents, versions.get(showId) ?? 0, own);
}
const withTransaction: WithTransaction = (work) =>
work({
sales: {
saleOf: async (showId) => saleOf(showId),
saleOfOrder: async (token) => {
const order = orders.find((one) => one.token === token);
return order === undefined ? undefined : saleOf(order.showId);
},
save: async (sale) => {
if ((versions.get(sale.showId) ?? 0) !== sale.version) {
throw new SaleChangedError(`The sale of show ${sale.showId} changed after version ${sale.version}.`);
}
versions.set(sale.showId, sale.version + 1);
const { added, changed } = sale.changes();
for (const order of added) {
orders.push({ showId: sale.showId, token: order.token, details: order.details, state: order.state });
}
for (const order of changed) {
orders.find((one) => one.token === order.token)!.state = order.state;
}
},
},
issueTickets: async (orderToken, newTickets) => {
tickets.push(...newTickets.map((ticket) => ({ ...ticket, orderToken })));
},
});
return { withTransaction, orders, tickets };
}
It stores what a row would hold, not the Order objects. Each saleOf rebuilds the orders with Order.restore, so a test cannot change a stored order behind the sale’s back. It keeps the version check, too, so a test sees the same SaleChangedError as the web app.
It lives in application/, because it imports only domain/ and the port types, and the dependency rule accepts it there. Cockburn describes this setup, with tests that drive the application and an in-memory database in place of the real one.
Now Omar’s test, and three more. Save this as src/sales/application/sales.test.ts:
import assert from "node:assert/strict";
import { test } from "node:test";
import { parseCents } from "#money";
import { inMemorySales } from "./in-memory.ts";
import { salesService } from "./sales.ts";
const ana = { name: "Ana", email: "ana@tinytickets.example" };
const tenOClock = new Date("2027-03-01T10:00:00Z");
// Show 1 has 2 seats at $12, stored in memory. Nothing here needs PostgreSQL,
// Express or the payment provider.
function salesOnShowOne() {
const store = inMemorySales([{ id: 1, seats: 2, priceCents: parseCents(1200) }]);
const service = salesService({
withTransaction: store.withTransaction,
startPayment: async (orderToken) => `/pay/${orderToken}`,
queueConfirmation: async () => {},
now: () => tenOClock,
});
return { store, service };
}
test("a buyer who asks for more seats than are left is told how many are left", async () => {
const { store, service } = salesOnShowOne();
const hold = await service.holdSeats(1, ana, [{ kind: "standard", quantity: 3 }]);
assert.deepEqual(hold, { result: "sold out", seatsLeft: 2 });
assert.deepEqual(store.orders, []);
});
test("a hold is saved with its price, and the buyer is sent to pay", async () => {
const { store, service } = salesOnShowOne();
const hold = await service.holdSeats(1, ana, [{ kind: "standard", quantity: 1 }, { kind: "student", quantity: 1 }]);
const order = store.orders[0]!;
assert.deepEqual(hold, { result: "held", payUrl: `/pay/${order.token}` });
assert.equal(order.details.totalCents, 2310);
});
test("a payment issues one ticket per seat, at the price of its kind", async () => {
const { store, service } = salesOnShowOne();
await service.holdSeats(1, ana, [{ kind: "standard", quantity: 1 }, { kind: "student", quantity: 1 }]);
const token = store.orders[0]!.token;
await service.markOrderPaid({ orderToken: token, paymentId: "pay_1", amountCents: parseCents(2310) });
assert.deepEqual(store.tickets.map((ticket) => [ticket.kind, ticket.priceCents]), [["standard", 1200], ["student", 960]]);
});
test("a failed payment gives the seats to the next buyer", async () => {
const { store, service } = salesOnShowOne();
await service.holdSeats(1, ana, [{ kind: "standard", quantity: 2 }]);
const token = store.orders[0]!.token;
await service.cancelOrder({ orderToken: token, paymentId: "pay_2", amountCents: parseCents(2550) });
const next = await service.holdSeats(1, ana, [{ kind: "standard", quantity: 2 }]);
assert.equal(next.result, "held");
});
The first test is Omar’s, with the same name and the same expected answer, plus one more check that nothing was saved. The show has two seats because the test says so, not because of what another test left in a table.
Then give the tests that need no database a script of their own. In package.json, add this line after "test" (an excerpt):
"test:fast": "node --test \"src/**/*.test.ts\" \"test/**/*.test.ts\"",
The two patterns match every test file under src/ and test/, which is every test except app.test.ts. The script reads no .env file, because nothing it runs connects to anything.
Run the new tests alone:
node --test src/sales/application/
What you should see (an excerpt from one run):
✔ a buyer who asks for more seats than are left is told how many are left (3.053647ms)
✔ a hold is saved with its price, and the buyer is sent to pay (0.417446ms)
✔ a payment issues one ticket per seat, at the price of its kind (0.714296ms)
✔ a failed payment gives the seats to the next buyer (0.437093ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
Omar’s test took 3 ms in that run, against 38 ms and a 10-second wait in the problem section. Now stop the container, as on Nina’s laptop.
Pause and predict: with no PostgreSQL running, what do
npm run test:fastandnpm testeach do?
docker stop tinytickets-db
npm run test:fast
npm test
What you should see (two excerpts from one run; your times will differ):
> test:fast
> node --test "src/**/*.test.ts" "test/**/*.test.ts"
...
✔ domain/ and application/ import nothing from the outside world (3.337788ms)
ℹ tests 26
ℹ suites 0
ℹ pass 26
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 306.150429
> test
> node --env-file=.env.test migrate.ts && node --env-file=.env.test --test
node:internal/modules/run_main:111
triggerUncaughtException(
^
AggregateError [ECONNREFUSED]:
...
Error: connect ECONNREFUSED ::1:5546
In that run, the 26 tests that need no database took 0.3 seconds. They are the domain tests, the application tests, the money and payout tests, and the two boundary tests. npm test stopped at the migration, as it did on Nina’s laptop.
Start PostgreSQL again with the commands under “Start PostgreSQL” in README.md. The container was started with --rm, so stopping it deleted both databases. Then run npm run migrate and npm run seed for the app database, and npm test.
What you should see: all 44 tests pass: the 26 above and the 18 in app.test.ts (an excerpt).
ℹ tests 44
ℹ suites 0
ℹ pass 44
ℹ fail 0
app.test.ts stays, and it matters more now. The in-memory adapter keeps no rollback and runs no SQL. So it cannot show that the PostgreSQL adapter writes the right rows, or that the version check holds under 50 requests at once. Nor can it show that the transaction undoes a failed payment. Those tests are the adapter’s tests. Commit:
git add -A
git commit -m "Test the commands without a database"
Step 7: Update the glossary, the README and the code figure
Why: the glossary still names changeSale, saveSale and services/, and none of them exist.
What to do: in GLOSSARY.md, replace the code line of the “Sale” entry with this:
- Code: the aggregate `Sale` (`src/sales/domain/sale.ts`), with `hold`,
`pay`, `cancel`, `seatsLeft` and `tickets`; its orders are `Order`
entities. Stored through the port `SaleRepository`
(`src/sales/domain/sale-repository.ts`); its PostgreSQL adapter
(`src/sales/db/sale-repository.ts`) writes table `sales.sales`, one row
per show with a `version`. A show is on sale as soon as its row is in
`shows.shows` (see the hotspot under "Sale opened" in `BOARD.md`).
Four other entries name a moved file. In “Hold”, holdSeats is now in src/sales/application/sales.ts, and so is the type Payment in “Payment”. In “Booking fee”, bookingFeeCents is in src/sales/domain/pricing.ts. Replace the code line of “Order” with this:
- Code: the entity `Order` (`src/sales/domain/order.ts`), with `pay`,
`cancel` and `holdsSeats`; the buyer, the lines and the total are its
`details`. An order belongs to the sale of its show, and the web app
changes it only through `Sale`. Table `sales.orders`, read and written
through `orderFromRow`, `insertOrder` and `saveOrderState`
(`src/sales/db/orders.ts`); the CHECK `orders_one_state` keeps one state
per row. The lines: column `sales.orders.lines`, type `OrderLine`
(`src/sales/domain/pricing.ts`).
In README.md, replace the paragraph about src/sales/domain/sale.ts with these two:
`src/sales/domain/sale.ts` holds the `Sale` aggregate: the seats of one show
and its orders, with the rule that the orders never take more seats than the
show has. Holds and payments change a sale through the application services
in `src/sales/application/sales.ts`, which load and save it through the
`SaleRepository` port and try again when another request saved the same sale
first.
Inside Sales, `domain/` and `application/` import nothing from Express,
`pg` or `#platform`; `test/boundaries.test.ts` fails when they do. The
adapters sit around them: `routes/` for HTTP, `db/` for PostgreSQL, and
`src/sales/wiring.ts` picks the adapter for each port.
`src/sales/application/in-memory.ts` is a second adapter, for tests.
Under “Check and test” in the same file, add npm run test:fast # every test except app.test.ts; needs no database under the other two commands, and line up their comments. CONTEXT-MAP.md does not change: no arrow between contexts moved. Figure 6 is the code figure with the new layers marked.
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Shows}, {Sales}, {Payouts} ..> money/ the shared kernel (#money)
Inside {Sales}: routes/ ..> wiring.ts ..> application/ ..> domain/
db/, jobs/, acl/ ..> application/; db/, jobs/ ..> domain/
domain/ Sale, Order, pricing (a domain service), and
the port SaleRepository; imports only
domain/ and #money NEW
application/ salesService: one function per command, the
transaction and the retry; ports
WithTransaction, startPayment NEW
db/ the PostgreSQL adapters NEW; ..> {Shows}
findShow on the transaction's client
wiring.ts the composition root NEW
routes/ ..> acl/ ACL ..> [Payment provider]
A test fails when domain/ or application/ imports
anything else NEW.
platform/ the pool, the job queue, settings, page layout, login, email,
the payment provider's client, the organizer dashboard.
Every context ..> platform/. platform/ ..> money/.
app.ts and worker.ts ..> each #.
Figure 6: the arrows between contexts did not change; inside Sales, every arrow now points toward domain/.
Run the checks:
npm run check
npm test
npm run test:fast
What you should see: no tsc errors, 44 tests pass in npm test, and 26 in npm run test:fast. The end of the fast run, from one run:
✔ a sale holds seats until it has none left (3.2841ms)
✔ a hold that ran out gives its seats to the next buyer (0.444336ms)
✔ a paid order keeps its seats after its hold would have run out (0.415393ms)
✔ two copies of one sale both give away its last seat (0.232625ms)
✔ a hold for one student ticket is priced with the booking fee (0.288274ms)
✔ a paid order gets one ticket per seat, at the price of its kind (0.380805ms)
✔ a sale lists the orders it added and the ones it changed (0.508101ms)
✔ a context imports another context only through its # entry (15.989476ms)
✔ domain/ and application/ import nothing from the outside world (3.122991ms)
ℹ tests 26
ℹ suites 0
ℹ pass 26
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 285.3055
Commit:
git add -A
git commit -m "Describe the ports and adapters in the glossary and the README"
How a hold works now
Follow Ana, who asks for two standard tickets for show 7 (Figure 7):
holdRoutesreads the form, as before, and callssales.holdSeats(7, buyer, lines).salesis the servicewiring.tsbuilt with the PostgreSQL adapters.holdSeatscallsinTransaction, which calls the portwithTransaction. The adapter indb/transaction.tstakes one client from the pool and runsBEGIN.- The work asks
sales.saleOf(7). The PostgreSQL repository callsfindShow(7, client)on the same client, reads the version and the orders of show 7, and maps them withorderFromRowandSale.restore. sale.hold(token, buyer, lines, now)prices the order throughorderTotalCents, counts the free seats, and adds a heldOrder. No input or output happens in this step.sales.save(sale)moves the version from 4 to 5, or throwsSaleChangedErrorif another request saved first. Then it inserts the one order inchanges().added.withTransactionrunsCOMMITand releases the client. When the work throws, it rolls back instead. OnSaleChangedError,inTransactionthen runs steps 2 to 6 again, up to three times.- After the commit,
holdSeatscalls the portstartPayment.wiring.tsasks the provider for a payment page and stores it on the order. - The route answers 303 to the payment page.
(Ana) --> [Web app] routes/holds.ts a driving adapter
--> sales.holdSeats application/sales.ts
inTransaction --> withTransaction db/transaction.ts: BEGIN
sales.saleOf(7) db/sale-repository.ts
..> {Shows} findShow(7, client)
<-- [[sales.sales]] version 4, [[sales.orders]] of show 7
sale.hold domain/sale.ts, pricing.ts: no I/O
sales.save --> [[sales.sales]] version 5
--> [[sales.orders]] the new order
COMMIT
startPayment wiring.ts --> [Payment provider]
(Ana) <-- 303 to the payment page
Figure 7: the route calls in, the service decides where the transaction starts and ends, and only adapters touch PostgreSQL.
In Omar’s test, the same service runs with inMemorySales in place of the PostgreSQL adapters in steps 2, 3, 5 and 6. Step 7 calls a function that returns /pay/<token>. Step 4 and the retry run unchanged. A payment follows the same path with saleOfOrder, pay and tickets.
Going deeper
Layers, ports and adapters, rings, or a functional core
Sales now uses ports and adapters. Figure 8 compares it with the other ways to keep the domain apart from its technology.
| Option | What it is | When it wins | Source |
|---|---|---|---|
| Layers | UI, application, domain, infrastructure; each depends on the one below | a small app, or a team that already works in layers; the domain still depends on infrastructure unless you invert that one arrow | Evans, Reference, p. 10 |
| Ports and adapters (this module) | the domain and application in the middle; every technology behind a port | several ways in (HTTP, worker, tests) and out (database, provider, email), and domain tests that must be fast | Cockburn, 2005 |
| Clean or Onion architecture | the same direction of imports, with more named rings | the same cases as ports and adapters; it costs more names and folders | Martin, 2012 |
| Functional core, imperative shell | read everything, decide with a pure function, then write | a command that can read all its input before it decides, with no read in the middle | Seemann, 2016 and 2020 |
Figure 8: four ways to keep the rules apart from the technology; the last three share the dependency rule.
Cockburn argues against the layered drawing itself, for the two kinds of boundary above. Evans (p. 10) presents layers, then says a hexagonal architecture may serve as well or better. Martin’s essay lists Hexagonal, Onion and three other architectures as variants of one rule.
Mark Seemann, in “Functional architecture is Ports and Adapters” (2016), argues that a pure core with impure edges reaches the same shape with less ceremony. He calls keeping Dependency Injection disciplined in object-oriented code a “Sisyphean task”. In “Impureim sandwich” (2020) he names the shape: an impure read, a pure decision, an impure write. He finds it possible often, but does not claim it always is.
holdSeats is that sandwich already. saleOf reads, sale.hold decides with now passed in, and save writes. The ports still earn their place for the parts that do not fit, such as the payment page after the commit.
What the authors meant, and where they disagree
On how many repositories, Evans (p. 17) and Vernon (Part II, p. 8) give one to each aggregate root that must be found directly. Design Patterns in Plain Words Module 7 shows the general pattern, one repository per kind of stored record, which fits code with no aggregates. A generic Repository<T> with findWhere(predicate) is a third option. Evans’ rule that a repository selects by criteria a domain expert would name argues against it, because any caller could then reach into an aggregate; that reading is ours.
On what a repository returns, Evans says whole aggregates. Vernon (Part III, p. 14) accepts a method that returns a sum computed in SQL when loading every object only to add them up would be wasteful. TinyTickets has no such method; Module 10 answers the dashboard’s sums with a read model instead.
On what the service layer holds, Fowler’s Service Layer controls transactions and coordinates, and the DDD application service does the same with one restriction. Evans’ description, as Fowler quotes it, keeps the layer thin and free of business rules. Fowler’s “AnemicDomainModel” warns about the opposite case. When the rules sit in services, the domain objects are left as data with no behavior.
Martin adds a rule for what crosses a boundary. Simple data structures may cross, and database rows should not be passed inward. In TinyTickets the mapper stops the rows at db/, and only Sale and Order reach application/.
What changed recently
pg, the driver, changed in ways the adapter touches. Version 8.19.0, in 2026, deprecated the client’s internal query queue, which lets a client accept a second query while one is still running, and printed a warning for it. The maintainer later said he would remove the warning and deprecate the queue in a less disruptive way. A transaction’s queries should run one after another anyway, as the adapter’s await on each query does. Later in 2026, 8.21.0 added client.getTransactionStatus(), and 8.23.0 added support for query pipelining. All three are in the node-postgres changelog.
getTransactionStatus() reports whether the client is idle, in a transaction, or in a failed one. An adapter could use it to refuse work outside a transaction. TinyTickets does not need that, because only withTransaction builds the repository.
The DDD sources this module uses have not changed since they were published: Cockburn (2005), Vernon (2011), Martin (2012) and Evans’ Reference (2015).
When ports and adapters are too much
Skip the port when a context has no rule to protect. A read-only report, or an admin screen that edits a name, gains nothing from an interface. A route that calls one query function is shorter, and its test against the test database is the only test it needs.
The pattern has a cost even where it fits. This module added seven files to Sales, one of them a test, and removed three. It also added mapping code to keep in step with the schema, and a fake that can drift from the real adapter. The fake has no rollback and runs no SQL, so app.test.ts must stay. If a command is “read, decide, write” and nothing else, a pure function with the reads and writes around it may be all you need. These limits are our judgment.
Check yourself
- In Step 2, why did the dependency rule test list
#platformand../db/sales.tsforapplication/holds.ts, but notnode:crypto?
Answer
The test is an allow-list. application/ may import only domain/, application/, #money and a few node: modules that do no input or output, and node:crypto is one of them. #platform brings the pool, and ../db/ is an adapter, so both point outward.
- Where does the
SaleRepositoryinterface live, where does its PostgreSQL adapter live, and why that way round?
Answer
The interface is in domain/, and the adapter is in db/. The adapter imports the interface, so the import points inward, while at run time the application service calls out through it. That keeps domain/ free of pg, which the dependency rule test checks.
- Why is there no
OrderRepository, and what wouldpghand the mapper for abigintcolumn?
Answer
An order lives inside a sale and changes only through the Sale root, and a repository exists for an aggregate root that must be found directly. An OrderRepository would let code change an order without the seat rule and the version. A bigint arrives as a string, so the mapper is the place to parse it before it reaches the domain.
pricing.tsandsalesServiceare both services. What makes one a domain service and the other an application service?
Answer
pricing.ts holds a business rule, the price of a ticket and of an order, with no input or output, so it lives in domain/. salesService holds no rule: it loads a sale, calls one method on it, saves it, and owns the transaction and the retry, all through ports.
- The in-memory adapter passes every test. What can it not prove?
Answer
It runs no SQL and keeps no rollback. So it cannot show that the PostgreSQL adapter writes the right rows, or that the version check holds when 50 requests arrive at once. Nor can it show that a failed command leaves nothing behind. app.test.ts keeps those checks.
Exercise: let the test choose the time
A payment that arrives after the hold ran out must issue no tickets. app.test.ts checks a late payment by moving hold_expires_at back with SQL, and then reads the order’s row. Write it as an application test instead, in src/sales/application/sales.test.ts, with a clock the test can move. Undo it at the end.
Solution
now is a port, so the test passes a function that reads a variable, and changes the variable between the hold and the payment:
test("a payment after the hold ran out issues no tickets", async () => {
let now = tenOClock;
const store = inMemorySales([{ id: 1, seats: 2, priceCents: parseCents(1200) }]);
const service = salesService({
withTransaction: store.withTransaction,
startPayment: async (orderToken) => `/pay/${orderToken}`,
queueConfirmation: async () => {},
now: () => now,
});
await service.holdSeats(1, ana, [{ kind: "standard", quantity: 1 }]);
now = new Date(tenOClock.getTime() + 11 * 60_000);
const token = store.orders[0]!.token;
await service.markOrderPaid({ orderToken: token, paymentId: "pay_3", amountCents: parseCents(1350) });
assert.deepEqual(store.tickets, []);
assert.equal(store.orders[0]!.state.status, "cancelled");
});
One run printed this (an excerpt; the token is random):
Order 6bfa8741e0fe7b719ac349e96884fdbc was cancelled before payment pay_3 came. Refund it by hand.
...
✔ a payment after the hold ran out issues no tickets (1.638929ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
The log line is the service’s own, printed after the commit. Eleven minutes after a 10-minute hold, pay returns "too late" and cancels the order, so the service issues no tickets. Undo the exercise:
git checkout src/sales/application/sales.test.ts
Cheat sheet
Cheat sheet
- Dependency rule: imports point inward;
domain/imports onlydomain/and#money, and a test checks it.- Port: an interface the inside owns, in its own words (
SaleRepository,WithTransaction); import it withimport type.- Adapter: connects one technology to a port; driving ones call in (routes, tests), driven ones are called (
db/, the provider).- Repository: one per aggregate root, whole aggregates in and out, version check inside
save; not a Git repository.- Mapping: a row becomes an object through
restore;pgreturnsbigintandnumericas strings, anddateat local midnight.- Application service: one command; load, call one method, save; owns the transaction and the retry; no rules.
- Domain service: a rule that belongs to no one object, with no I/O (
pricing.ts).- Costs: more files, mapping to keep in step, and a fake that can drift; keep tests against PostgreSQL.
- Skip it: when a context has no rule to protect, or one pure function between a read and a write is enough.
Figure 9 is the whole module in one picture.
Drive routes/, sales.test.ts --> salesService (application/)
Load sales.saleOf / saleOfOrder port SaleRepository (domain/)
Decide sale.hold / pay / cancel domain/, pricing.ts: no I/O
Save sales.save version check, then the changed orders
Adapters db/ (PostgreSQL) in-memory.ts (tests)
Wire wiring.ts the composition root of Sales
Check test/boundaries.test.ts domain/ and application/ import no pg
Figure 9: the command goes in through a driving adapter, decides in the domain, and leaves through ports.
Sales now has three rings: the domain, the application services, and the adapters around them. Omar’s test and 25 others run in about 0.3 seconds with no database, and npm test still runs all 44 against PostgreSQL. Next, Module 9 deals with what happens after the commit, because a buyer gets a confirmation email for an order whose transaction rolled back.
Sources
- Alistair Cockburn, “Hexagonal Architecture”, 2005.
- Eric Evans, Domain-Driven Design Reference: Definitions and Pattern Summaries, Domain Language, 2015 (CC BY 4.0). Layered Architecture (p. 10), Services (p. 14), Repositories (p. 17).
- Robert C. Martin, “The Clean Architecture”, 2012.
- Vaughn Vernon, “Effective Aggregate Design”, 2011: Part I (p. 3), Part II (p. 8), Part III (p. 14).
- Martin Fowler, Service Layer, catalog of Patterns of Enterprise Application Architecture, 2002, and “AnemicDomainModel”, 2003.
- Mark Seemann, “Functional architecture is Ports and Adapters”, 2016, and “Impureim sandwich”, 2020.
- node-postgres: Data types, Transactions, changelog.
- Design Patterns in Plain Words: Module 6, Dependency Injection, and Module 7, Talking to the Database.