At 10:12 on Saturday, a buyer paid for two tickets to Leo’s show, two minutes after her hold ran out. Her order page said “This order was cancelled.”, so Maya refunded her by hand on the payment provider’s site.
At 10:31 the provider’s webhook for that payment arrived, and TinyTickets emailed her the two tickets. On Monday, Nina found the order in the database, with status set to paid and a cancelled_at of 10:10.
“Is this order paid or cancelled?” Leo asked. “It can’t be both.”
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
The buyer had her money back and two tickets that the door would accept. Nina found the order before the show, so nobody got in for free, and it stayed a near miss. It is the hotspot from Kofi’s question in Module 2, this time with a refund.
This module makes the order an entity: an object with one identity that moves from held to paid or to cancelled, and is never in two states at once. A TypeScript union makes the paid-and-cancelled order impossible to write, and the order’s own methods decide what a late webhook does.
After this module, you can:
- say what makes an order an entity, which value is its identity, and where that identity comes from
- write an entity’s states as a discriminated union, so that
tscrefuses an order that is paid and cancelled at once, and names a state that aswitchforgot - create and load an entity only through factories, behind a private constructor
- keep the rules for changing state inside the entity’s methods, including a rule that depends on the clock
- recognize an anemic domain model, and say when a row with no methods is the better choice
Where the code stands
Module 5 gave money its own type, Cents, in a shared kernel. The order is still a row: the type Order in src/sales/db/orders.ts has the shape of sales.orders, and the files that read or write its status each decide what it means. Figure 1 is the code figure from Module 5, with the kernel’s line shortened.
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Shows}, {Sales}, {Payouts} ..> money/ the shared kernel (#money)
Inside {Sales}: 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 and their arrows as Module 5 left them; inside Sales, no part of the code owns the order’s states.
A late webhook leaves an order paid and cancelled
Two functions in src/sales/services/orders.ts change an order’s status. The first runs when a payment arrives (an excerpt, lines 16 to 23):
const order = await findOrderByToken(payment.orderToken, client);
// The payment service may send the same webhook twice.
if (order === undefined || order.status === "paid") {
await client.query("ROLLBACK");
return;
}
// A buyer who paid after the hold ran out still gets the tickets.
await client.query("UPDATE sales.orders SET status = 'paid', paid_at = now() WHERE id = $1", [order.id]);
The second runs when a payment fails (lines 48 to 53):
export async function cancelOrder(payment: Payment): Promise<void> {
await pool.query(
"UPDATE sales.orders SET status = 'cancelled', cancelled_at = now() WHERE token = $1",
[payment.orderToken],
);
}
markOrderPaid stops only for an order that is already paid, and cancelOrder does not look at the order at all. Add two tests at the end of app.test.ts, one for each order of news:
// One standard ticket for the other show: 2000 cents and the 150 booking fee.
async function holdOneTicket(): Promise<{ token: string; payment_id: string }> {
const show = await pool.query("SELECT id FROM shows.shows WHERE name = 'Other Show'");
await post(`/shows/${show.rows[0].id}/hold`, { ...buyer, standard: "1" });
const order = await pool.query("SELECT token, payment_id FROM sales.orders ORDER BY id DESC LIMIT 1");
return order.rows[0];
}
async function stateOf(token: string): Promise<unknown[]> {
const order = await pool.query(
`SELECT status, paid_at IS NOT NULL AS paid, cancelled_at IS NOT NULL AS cancelled
FROM sales.orders WHERE token = $1`,
[token],
);
return order.rows;
}
test("a payment after the hold ran out leaves the order cancelled", async () => {
const { token, payment_id } = await holdOneTicket();
await pool.query("UPDATE sales.orders SET hold_expires_at = now() - interval '1 minute' WHERE token = $1", [token]);
await expireHolds();
const answer = await webhook({
id: "evt_5",
type: "payment.succeeded",
data: { payment_id, amount_cents: 2150, currency: "usd", metadata: { order_ref: token } },
});
assert.equal(answer.status, 200);
assert.deepEqual(await stateOf(token), [{ status: "cancelled", paid: false, cancelled: true }]);
});
test("a failed payment after a received one leaves the order paid", async () => {
const { token, payment_id } = await holdOneTicket();
const data = { payment_id, amount_cents: 2150, currency: "usd", metadata: { order_ref: token } };
await webhook({ id: "evt_6", type: "payment.succeeded", data });
const answer = await webhook({ id: "evt_7", type: "payment.failed", data });
assert.equal(answer.status, 200);
assert.deepEqual(await stateOf(token), [{ status: "paid", paid: true, cancelled: false }]);
});
holdOneTicket uses the other test show, because Leo’s test show has no free seats by this point in the file. The first test moves the hold back by a minute, lets expireHolds cancel it, and then sends the payment, as in the scene. The second test sends a payment and then a failure for the same payment.
Pause and predict: the first order is already cancelled when its payment arrives. What does
stateOfreturn for it after the webhook?
npm test
What you should see (an excerpt; your timings will differ):
✖ a payment after the hold ran out leaves the order cancelled (15.68416ms)
✖ a failed payment after a received one leaves the order paid (14.481009ms)
...
ℹ tests 25
ℹ suites 0
ℹ pass 23
ℹ fail 2
...
actual: [ { status: 'paid', paid: true, cancelled: true } ],
expected: [ { status: 'cancelled', paid: false, cancelled: true } ],
...
actual: [ { status: 'cancelled', paid: true, cancelled: true } ],
expected: [ { status: 'paid', paid: true, cancelled: false } ],
The first order is paid, and its cancelled_at is still set, like Nina’s row. The second is the same bug in the other direction. A failure that arrives after the payment cancels a paid order, which keeps its paid_at and its tickets. Both can happen in production, because a payment provider sends a webhook again when the first try does not get through, so news can arrive late and out of order.
Figure 2 reads the row from the scene through every file that asks about an order’s status.
| File | Its rule | The row from the scene |
|---|---|---|
src/door/routes/door.ts:24 |
refuse unless order_status is "paid" |
admits her |
src/sales/db/tickets.ts:42, for Payouts |
status = 'paid' AND cancelled_at IS NULL |
leaves her tickets out of Leo’s payout |
src/platform/db/dashboard.ts:16-17 |
status = 'paid' |
counts her tickets as sold |
src/sales/routes/holds.ts:41 |
"paid", or "pending" before hold_expires_at |
counts her seats as taken |
Figure 2: four rules about one row, two in TypeScript and two in SQL, and they disagree.
Payouts gets the right answer only by luck, because Maya refunded the money. Each file holds its own copy of the rules, and the table lets status, paid_at and cancelled_at disagree. Nothing in the code says which states an order can be in, or how it moves between them.
An order is an entity with a lifecycle
An entity keeps its identity while it changes
An entity is an object that the model tells apart by its identity, not by its attributes, and that stays the same object while its attributes change. Evans’ Domain-Driven Design Reference (2015, p. 11) describes such an object as a thread of identity that runs through a lifecycle, and warns that mistaken identity corrupts data. His rule for the model is one line:
“The model must define what it means to be the same thing.” (Evans, Domain-Driven Design Reference, p. 11)
The buyer’s order was held at 10:00, cancelled at 10:10 and paid at 10:31, and it was one order the whole time. Two orders by the same buyer, for the same show and the same tickets, are still two orders. That is the opposite of a value object from Module 5, where 1110 cents is the same amount wherever it appears. In many ORMs, “entity” is the name for a class mapped to a table. The DDD entity is about identity, and a value object can be stored in a table too.
Identity is the value that says which entity an object is. A sales.orders row has two candidates. id is an identity column, so PostgreSQL assigns it during the INSERT.
token is 16 random bytes in hex, made by createHold before the INSERT, and it is the value that the buyer’s link and the payment provider know the order by. So the token is the order’s identity in the model, and id stays the row’s key for sales.tickets.
JavaScript compares objects by reference, so the code must compare tokens. Save this as try-identity.ts in the project folder after Step 2, when Order exists:
import { Order } from "./src/sales/domain/order.ts";
const state = { status: "held", holdExpiresAt: new Date("2027-03-01T10:10:00Z") } as const;
const first = Order.restore("4be0c1d2", state);
const second = Order.restore("4be0c1d2", state);
console.log(first === second, first.token === second.token);
console.log(JSON.stringify(first));
Run node try-identity.ts, then delete the file.
What you should see:
false true
{"token":"4be0c1d2"}
Two loads of one order are two JavaScript objects and one entity. The second line comes back in the section on private fields. The cost of an entity starts here. Someone must choose the identity and keep it stable, and an identity that the database assigns does not exist until the row does.
One type for each state
Today an order’s state is a string plus two timestamps. Figure 3 compares three ways to write it.
Booleans { paid: boolean; cancelled: boolean } paid and cancelled compiles
A status string { status: "pending" | "paid" | "cancelled"; paid with a cancelled_at
paid_at: Date | null; cancelled_at: ... } compiles
One type a state held { holdExpiresAt } | paid { paidAt } | no type has both
cancelled { cancelledAt }
Figure 3: the first two shapes can hold Nina’s row; the third cannot.
A discriminated union is a union of object types that share one property with a different literal type in each member (TypeScript handbook, Narrowing). TypeScript tells the members apart by that property. The shared property here is status:
export type OrderState =
| { readonly status: "held"; readonly holdExpiresAt: Date }
| { readonly status: "paid"; readonly paidAt: Date }
| { readonly status: "cancelled"; readonly cancelledAt: Date };
After a check such as state.status === "held", TypeScript narrows the type to the member that matches. So state.holdExpiresAt compiles only inside that check, because only a held order has a time when its hold runs out.
It works because the paid member has no cancelledAt property, so an object literal that has one is not an OrderState. Step 2 shows the tsc error. The names follow Leo’s words. The state is “held”, as the glossary from Module 1 says, and the old value 'pending' goes away in Step 1.
The cost is more types, and code that must narrow before it reads a field. The database still stores one row with nullable columns, so loading an order needs a function that turns the row into the right member (Step 3).
Figure 4 shows the moves between the states. An arrow here is a change of state, not a request.
held -- pay(), before the hold runs out -------------------> paid
held -- the hold runs out, cancel(), or a late pay() ------> cancelled
paid stays paid: pay() and cancel() return "already paid"
cancelled stays cancelled: pay() returns "too late", cancel() "already cancelled"
Figure 4: an order starts held and ends in one of two states that never change again.
Let tsc name the state a switch forgot
The never type has no values, so nothing can be assigned to it (TypeScript handbook, Narrowing).
An exhaustiveness check is a default branch of a switch that passes the value to a function that takes never. When every state has a case, the value in default has type never, and the call compiles. When someone adds a state, tsc reports every switch that does not handle it. Here is the helper (an excerpt of src/sales/domain/order.ts):
function assertNever(state: never): never {
throw new Error(`Unknown order state: ${JSON.stringify(state)}`);
}
The throw runs only if a value that the types did not expect reaches default at run time, such as a row with a status the code has never seen. The exercise at the end adds a state and shows the errors.
The cost is that the check covers only the switches that have it. A rule written as state.status === "paid" || ... compiles without a change when a new state appears, so it gives the new state an answer that nobody chose.
A private constructor and two factories
A private constructor is a constructor that only code inside the class can call, so new Order(...) anywhere else fails to compile (TypeScript 2.0 release notes). A factory is a function that creates objects for its caller, so the caller does not use new (Design Patterns in Plain Words, Module 2). Order has two:
Order.hold(token, now)makes a new order. It writes the rule that a new order starts held forHOLD_MINUTES, so no caller can make an order that starts paid.Order.restore(token, state)rebuilds an order that already exists, from a state that was stored earlier.
Evans (Reference, p. 18) moves creation into a factory when it is complicated, and asks the factory to create the whole object as one piece, with its invariants enforced. He writes this for aggregates, which Module 7 introduces. With the constructor private, these two are the only ways to get an Order.
TypeScript’s private exists only for tsc. Type stripping removes it, so plain JavaScript can still call the constructor. The handbook calls such members “soft private”, because code can still read them with bracket notation (TypeScript handbook, Classes). An ECMAScript private field is a field whose name starts with #, such as #state. JavaScript itself blocks every access to it from outside the class, at run time too (TypeScript 3.8 release notes).
Order keeps its state in #state and offers a read-only getter, state. That is why JSON.stringify printed only the token in the identity test. The cost is mapping code, because every place that stores an order must read order.state and write its columns by hand, as Step 3 does. And because Node.js strips types without changing code, the class declares each field on its own line, with no parameter properties, as Module 5 showed.
The rules live inside the methods
An invariant is a rule that holds every time code outside an object can look at it. The order has three:
- An order is in one state at a time.
- A failed payment never cancels a paid order.
- A cancelled order is never paid later.
The union carries the first rule. It cannot carry the other two, because they depend on the state the order was in before.
Evans (Reference, p. 22) asks you to state invariants, and to write automated tests for the ones the language cannot express. That is what the domain tests in Step 2 do.
A type also cannot know the time. An order loaded for a webhook has a state that is known only at run time. And a held order whose holdExpiresAt has passed is still "held" until the worker runs. So pay compares the time with the clock (an excerpt of src/sales/domain/order.ts):
// A payment counts only while the hold lasts. Leo's rule: a payment that
// comes later is refunded, because the seats may be sold again.
pay(now: Date): PaymentOutcome {
const state = this.#state;
switch (state.status) {
case "held":
if (state.holdExpiresAt <= now) {
this.#state = { status: "cancelled", cancelledAt: now };
return "too late";
}
this.#state = { status: "paid", paidAt: now };
return "paid";
case "paid":
return "already paid";
case "cancelled":
return "too late";
default:
return assertNever(state);
}
}
Leo made the rule. A buyer whose payment comes after the hold ran out gets her money back, because her seats were on sale again from that moment. The code cannot decide that; it can only keep Leo’s answer in one method. TinyTickets has no refund feature yet, so the caller logs the payment for a person to refund.
pay returns an outcome instead of throwing. A late payment is expected news, so the caller should handle it like any other answer. A throw stays for bugs, such as a state that assertNever did not expect. That split is our judgment; the DDD sources this module cites do not prescribe one.
Rule: the type removes the shapes that can never exist; the methods refuse the moves that depend on the past or on the clock.
What the method cannot stop is two webhooks for one order at the same moment. Both could load a held order and both could pay it. Module 7 adds the guard against that.
Rules in services make an anemic domain model
An anemic domain model is a set of objects named after the domain that hold data and almost no behavior, while the rules live in services. Martin Fowler named it in “Anemic Domain Model” (2003) and called it an anti-pattern. His reason is that you pay the costs of a domain model, such as mapping, and get none of its benefits.
The Module 5 code is anemic in this sense. Order is a row type, and markOrderPaid, cancelOrder and expireHolds each write status with their own UPDATE. That is how one of them could forget a rule that another one knew.
The cure is to move the rules next to the data. A class with methods is one way.
A union type with functions in the same module, such as pay(order: Held): Paid, is another, and it keeps the rules beside the type too. Our reading of Fowler is that the problem is rules outside the model, not functions outside a class. A class with public setters and a status: string field is anemic, even though it is a class.
Give the order its states, step by step
Each step says why, what to do, the code, and what you should see. Work in the project folder Module 5 left, with the two tests from the problem section. The finished code is in the code/module-06/ folder of the course repository. If you kept the exercise from Module 4, your test counts are one higher.
Step 1: Store one state per order
Why: the type cannot keep the database honest. A CHECK constraint makes PostgreSQL refuse a row in two states, whichever code writes it.
What to do: save this as migrations/018_one_state_per_order.sql:
-- Year 3: an order is in one state at a time: held, paid or cancelled
-- (see "Order" in GLOSSARY.md).
-- A late webhook left some orders paid and cancelled. The first change wins,
-- as in the Order entity: cancelled before paid means cancelled.
UPDATE sales.orders SET status = 'cancelled', paid_at = NULL
WHERE paid_at IS NOT NULL AND cancelled_at IS NOT NULL AND cancelled_at < paid_at;
UPDATE sales.orders SET status = 'paid', cancelled_at = NULL
WHERE paid_at IS NOT NULL AND cancelled_at IS NOT NULL;
-- Orders from before migration 010 have no paid_at or cancelled_at.
UPDATE sales.orders SET paid_at = created_at WHERE status = 'paid' AND paid_at IS NULL;
UPDATE sales.orders SET cancelled_at = created_at WHERE status = 'cancelled' AND cancelled_at IS NULL;
-- Leo's word for an order that waits for its payment is "held".
ALTER TABLE sales.orders DROP CONSTRAINT orders_status_check;
UPDATE sales.orders SET status = 'held' WHERE status = 'pending';
ALTER TABLE sales.orders ALTER COLUMN status SET DEFAULT 'held';
ALTER TABLE sales.orders ADD CONSTRAINT orders_one_state CHECK (
(status = 'held' AND paid_at IS NULL AND cancelled_at IS NULL)
OR (status = 'paid' AND paid_at IS NOT NULL AND cancelled_at IS NULL)
OR (status = 'cancelled' AND cancelled_at IS NOT NULL AND paid_at IS NULL)
);
A constraint over old rows needs the old rows fixed first, or ADD CONSTRAINT fails. The first two UPDATEs settle the rows in two states with the rule that pay follows, where the first change wins. Your test database has such rows, from the run in the problem section. On a real server, list them before you migrate, because every buyer whose order becomes cancelled needs a refund.
The next two UPDATEs fill the timestamps of orders from year 1, which migration 010 added without values. created_at is the closest time the table has. orders_status_check is the name PostgreSQL gave the constraint from migration 005.
Now say “held” in the code. In src/sales/db/orders.ts, change the type of status (an excerpt):
status: "held" | "paid" | "cancelled"; hold_expires_at: Date;
Run npm run check.
What you should see:
src/sales/pages/shows.ts(43,6): error TS7053: Element implicitly has an 'any' type because expression of type '"cancelled" | "held" | "paid"' can't be used to index type '{ pending: string; paid: string; cancelled: string; }'.
Property 'held' does not exist on type '{ pending: string; paid: string; cancelled: string; }'.
src/sales/routes/holds.ts(41,52): error TS2367: This comparison appears to be unintentional because the types '"cancelled" | "held"' and '"pending"' have no overlap.
The second error shows narrowing at work. On the right of order.status === "paid" ||, the status can no longer be "paid", so tsc lists only "cancelled" | "held". tsc cannot see the SQL strings, so grep -rn "pending" src app.test.ts finds the rest. Change all of them:
| File | Old | New |
|---|---|---|
src/sales/pages/shows.ts |
pending: in orderStates |
held: |
src/sales/routes/holds.ts |
order.status === "pending" |
order.status === "held" |
src/sales/jobs/expire-holds.ts |
status = 'pending' |
status = 'held' |
src/platform/db/dashboard.ts |
orders.status = 'pending' |
orders.status = 'held' |
app.test.ts |
status: "pending", status = 'pending' (three times), the variable pending |
status: "held", status = 'held', the variable held |
Run npm run check and npm test.
What you should see: npm run check prints no errors. The migration runs, and the two new tests still fail, now in a different way (an excerpt):
Applied 018_one_state_per_order.sql
...
✖ a payment after the hold ran out leaves the order cancelled (14.210513ms)
error: new row for relation "orders" violates check constraint "orders_one_state"
...
✖ a failed payment after a received one leaves the order paid (14.733892ms)
error: new row for relation "orders" violates check constraint "orders_one_state"
...
ℹ tests 25
ℹ suites 0
ℹ pass 23
ℹ fail 2
...
500 !== 200
PostgreSQL refused both UPDATEs, so the webhook answered 500. That is better than a row in two states, but not by much.
A provider sends a webhook again after an error, so the late payment would come back and fail again. The constraint says which rows are wrong; the order still needs code that knows what to do with late news. Commit:
git add -A
git commit -m "Store one state per order, and call it held"
Step 2: Write the Order entity
Why: the rules of Figure 4 need one home, which every caller must go through.
What to do: save this as src/sales/domain/order.ts:
// An order in Sales (see "Order" in GLOSSARY.md). The token is its identity:
// the buyer's link and the payment provider both know the order by it.
export const HOLD_MINUTES = 10;
// One type per state. Only a held order has a time when its hold runs out.
export type OrderState =
| { readonly status: "held"; readonly holdExpiresAt: Date }
| { readonly status: "paid"; readonly paidAt: Date }
| { readonly status: "cancelled"; readonly cancelledAt: Date };
export type OrderStatus = OrderState["status"];
export type PaymentOutcome = "paid" | "already paid" | "too late";
export type FailureOutcome = "cancelled" | "already cancelled" | "already paid";
export class Order {
readonly token: string;
#state: OrderState;
private constructor(token: string, state: OrderState) {
this.token = token;
this.#state = state;
}
// A new order starts with a hold of HOLD_MINUTES.
static hold(token: string, now: Date): Order {
return new Order(token, { status: "held", holdExpiresAt: new Date(now.getTime() + HOLD_MINUTES * 60_000) });
}
// An order that already exists, read back from storage.
static restore(token: string, state: OrderState): Order {
return new Order(token, state);
}
get state(): OrderState {
return this.#state;
}
// Paid orders and holds that have not run out take seats.
holdsSeats(now: Date): boolean {
const state = this.#state;
return state.status === "paid" || (state.status === "held" && state.holdExpiresAt > now);
}
// A payment counts only while the hold lasts. Leo's rule: a payment that
// comes later is refunded, because the seats may be sold again.
pay(now: Date): PaymentOutcome {
const state = this.#state;
switch (state.status) {
case "held":
if (state.holdExpiresAt <= now) {
this.#state = { status: "cancelled", cancelledAt: now };
return "too late";
}
this.#state = { status: "paid", paidAt: now };
return "paid";
case "paid":
return "already paid";
case "cancelled":
return "too late";
default:
return assertNever(state);
}
}
// A failed payment cancels a held order, and never a paid one.
cancel(now: Date): FailureOutcome {
const state = this.#state;
switch (state.status) {
case "held":
this.#state = { status: "cancelled", cancelledAt: now };
return "cancelled";
case "paid":
return "already paid";
case "cancelled":
return "already cancelled";
default:
return assertNever(state);
}
}
}
function assertNever(state: never): never {
throw new Error(`Unknown order state: ${JSON.stringify(state)}`);
}
HOLD_MINUTES moves here from src/sales/services/holds.ts, because the length of a hold is a rule of the order’s lifecycle. OrderStatus is derived from the union, so the list of statuses is written once. Each method takes now as an argument instead of reading the clock, so a test can pass any time it needs.
Order holds only its identity and its state. The buyer’s name, the lines and the total stay on the row, because no rule here needs them. Going deeper says why Evans asks for entities this lean.
Save the domain tests as src/sales/domain/order.test.ts:
import assert from "node:assert/strict";
import { test } from "node:test";
import { Order } from "./order.ts";
const tenOClock = new Date("2027-03-01T10:00:00Z");
const minutesLater = (minutes: number) => new Date(tenOClock.getTime() + minutes * 60_000);
test("a payment within the hold pays the order", () => {
const order = Order.hold("t1", tenOClock);
assert.equal(order.pay(minutesLater(9)), "paid");
assert.deepEqual(order.state, { status: "paid", paidAt: minutesLater(9) });
});
test("a payment after the hold ran out cancels the order", () => {
const order = Order.hold("t2", tenOClock);
assert.equal(order.pay(minutesLater(12)), "too late");
assert.equal(order.state.status, "cancelled");
});
test("a cancelled order is never paid later", () => {
const order = Order.hold("t3", tenOClock);
order.cancel(minutesLater(10));
assert.equal(order.pay(minutesLater(12)), "too late");
assert.equal(order.state.status, "cancelled");
});
test("a failed payment never cancels a paid order", () => {
const order = Order.hold("t4", tenOClock);
order.pay(minutesLater(2));
assert.equal(order.cancel(minutesLater(3)), "already paid");
assert.equal(order.state.status, "paid");
});
test("a hold takes seats until it runs out", () => {
const order = Order.hold("t5", tenOClock);
assert.equal(order.holdsSeats(minutesLater(9)), true);
assert.equal(order.holdsSeats(minutesLater(10)), false);
});
These tests need no database and no server, because the entity reads and writes nothing. Run them alone:
node --test src/sales/domain/order.test.ts
What you should see (an excerpt):
✔ a payment within the hold pays the order (1.632168ms)
✔ a payment after the hold ran out cancels the order (0.164545ms)
✔ a cancelled order is never paid later (0.190413ms)
✔ a failed payment never cancels a paid order (0.155649ms)
✔ a hold takes seats until it runs out (0.185682ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
Now ask tsc about the things the entity should refuse. Save this as src/sales/domain/try-order.ts:
import { Order } from "./order.ts";
import type { OrderState } from "./order.ts";
type OrderFlags = { paid: boolean; cancelled: boolean };
const flags: OrderFlags = { paid: true, cancelled: true };
const both: OrderState = { status: "paid", paidAt: new Date(), cancelledAt: new Date() };
function expiresAt(state: OrderState): Date {
return state.holdExpiresAt;
}
const order = new Order("t1", { status: "held", holdExpiresAt: new Date() });
Pause and predict: which of lines 5, 7, 10 and 13 compile?
Run npm run check.
What you should see:
src/sales/domain/try-order.ts(7,64): error TS2353: Object literal may only specify known properties, and 'cancelledAt' does not exist in type '{ readonly status: "paid"; readonly paidAt: Date; }'.
src/sales/domain/try-order.ts(10,16): error TS2339: Property 'holdExpiresAt' does not exist on type 'OrderState'.
Property 'holdExpiresAt' does not exist on type '{ readonly status: "paid"; readonly paidAt: Date; }'.
src/sales/domain/try-order.ts(13,15): error TS2673: Constructor of class 'Order' is private and only accessible within the class declaration.
Line 5 compiles, because two booleans can say paid and cancelled at once. Line 7 fails, because once status is "paid", tsc checks the literal against the paid member, which has no cancelledAt. Line 10 fails, because a paid or cancelled order has no holdExpiresAt, and the function did not narrow.
Line 13 fails, because only hold and restore may call new. Delete the file, and commit:
rm src/sales/domain/try-order.ts
git add -A
git commit -m "Add the Order entity"
Step 3: Load and save orders through the entity
Why: the entity changes nothing yet. Every function that reads or writes an order’s state must go through it.
What to do: replace src/sales/db/orders.ts with this:
import type pg from "pg";
import type { Cents } from "#money";
import type { OrderLine } from "../services/pricing.ts";
import { Order } from "../domain/order.ts";
import type { OrderStatus } from "../domain/order.ts";
import { pool } from "#platform";
export type OrderRow = {
id: number; token: string; show_id: number; buyer_name: string; buyer_email: string;
quantity: number; lines: OrderLine[]; total_cents: Cents;
status: OrderStatus; hold_expires_at: Date;
paid_at: Date | null; cancelled_at: Date | null; confirmation_sent_at: Date | null;
};
// 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 {
switch (row.status) {
case "held":
return Order.restore(row.token, { status: "held", holdExpiresAt: row.hold_expires_at });
case "paid":
return Order.restore(row.token, { status: "paid", paidAt: row.paid_at! });
case "cancelled":
return Order.restore(row.token, { status: "cancelled", cancelledAt: row.cancelled_at! });
}
}
export async function insertOrder(order: Order, r: {
showId: number; buyerName: string; buyerEmail: string;
quantity: number; lines: OrderLine[]; totalCents: Cents;
}): Promise<OrderRow> {
const state = order.state;
if (state.status !== "held") {
throw new Error(`Order ${order.token} is ${state.status}; a new order must be held.`);
}
const result = await pool.query<OrderRow>(
`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)
RETURNING *`,
[order.token, r.showId, r.buyerName, r.buyerEmail, r.quantity,
JSON.stringify(r.lines), r.totalCents, state.holdExpiresAt],
);
return result.rows[0]!;
}
// Writes the state of an order that is already stored.
export async function saveOrderState(order: Order, client: pg.PoolClient | pg.Pool = pool): Promise<void> {
const state = order.state;
await client.query(
"UPDATE sales.orders SET status = $2, paid_at = $3, cancelled_at = $4 WHERE token = $1",
[order.token, state.status,
state.status === "paid" ? state.paidAt : null,
state.status === "cancelled" ? state.cancelledAt : null],
);
}
export async function savePayment(id: number, paymentId: string, paymentUrl: string): Promise<void> {
await pool.query(
"UPDATE sales.orders SET payment_id = $1, payment_url = $2 WHERE id = $3",
[paymentId, paymentUrl, id],
);
}
export async function listOrdersForShow(showId: number): Promise<OrderRow[]> {
const result = await pool.query<OrderRow>("SELECT * FROM sales.orders WHERE show_id = $1", [showId]);
return result.rows;
}
export async function findOrderByToken(
token: string,
client: pg.PoolClient | pg.Pool = pool,
): Promise<OrderRow | undefined> {
const result = await client.query<OrderRow>("SELECT * FROM sales.orders WHERE token = $1", [token]);
return result.rows[0];
}
export async function markConfirmationSent(id: number): Promise<void> {
await pool.query("UPDATE sales.orders SET confirmation_sent_at = now() WHERE id = $1", [id]);
}
The row type is now OrderRow, so the name Order belongs to the entity. Three functions are new or changed:
orderFromRowturns a row into the matching member of the union. The!afterpaid_atis a promise totsc, and the constraint from Step 1 keeps it, as theCHECKon money columns did in Module 5.insertOrdertakes the entity.tsclets it readholdExpiresAtonly after the check that the order is held, so theifis the narrowing that line 10 oftry-order.tslacked.saveOrderStatewrites the three state columns fromorder.state. The other columns of an order never change after theINSERT.
Run npm run check.
What you should see:
src/sales/pages/shows.ts(1,15): error TS2459: Module '"../db/orders.ts"' declares 'Order' locally, but it is not exported.
src/sales/pages/shows.ts(43,6): error TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ held: string; paid: string; cancelled: string; }'.
src/sales/services/holds.ts(17,23): error TS2554: Expected 2 arguments, but got 1.
In src/sales/pages/shows.ts, import the row type under its new name, and use it in orderPage (an excerpt):
import type { OrderRow } from "../db/orders.ts";
export function orderPage(order: OrderRow, show: Show): string {
Replace src/sales/services/holds.ts, so that a new order comes from the factory:
import { randomBytes } from "node:crypto";
import { insertOrder, savePayment } from "../db/orders.ts";
import { Order } from "../domain/order.ts";
import type { Show } from "#shows";
import { createPayment } from "#platform";
import { orderTotalCents } from "./pricing.ts";
import type { OrderLine } from "./pricing.ts";
// Stores the order with its hold and asks the payment service for a payment page.
export async function createHold(
show: Show,
buyer: { name: string; email: string },
lines: OrderLine[],
): Promise<string> {
const totalCents = orderTotalCents(show.price_cents, lines);
const order = Order.hold(randomBytes(16).toString("hex"), new Date());
const row = await insertOrder(order, {
showId: show.id,
buyerName: buyer.name,
buyerEmail: buyer.email,
quantity: lines.reduce((sum, line) => sum + line.quantity, 0),
lines,
totalCents,
});
const payment = await createPayment(totalCents, order.token);
await savePayment(row.id, payment.id, payment.payUrl);
return payment.payUrl;
}
Now the two functions from the problem section. Replace src/sales/services/orders.ts with this:
import { randomBytes } from "node:crypto";
import type { Cents } from "#money";
import { enqueue, pool } from "#platform";
import { findOrderByToken, orderFromRow, saveOrderState } from "../db/orders.ts";
import { findShow } from "#shows";
import { insertTicket } from "../db/tickets.ts";
import { ticketPriceCents } from "./pricing.ts";
// A payment in Sales' words (see "Payment" in GLOSSARY.md).
export type Payment = { orderToken: string; paymentId: string; amountCents: Cents };
export async function markOrderPaid(payment: Payment): Promise<void> {
const client = await pool.connect();
try {
await client.query("BEGIN");
const row = await findOrderByToken(payment.orderToken, client);
if (row === undefined) {
await client.query("ROLLBACK");
return;
}
const order = orderFromRow(row);
const outcome = order.pay(new Date());
await saveOrderState(order, client);
if (outcome !== "paid") {
await client.query("COMMIT");
if (outcome === "too late") {
console.error(`Order ${order.token} was cancelled before payment ${payment.paymentId} came. Refund it by hand.`);
}
return;
}
await enqueue("send_confirmation", { payment });
const show = (await findShow(row.show_id))!;
for (const line of row.lines) {
for (let i = 0; i < line.quantity; i++) {
await insertTicket(client, {
showId: show.id, orderId: row.id, buyerName: row.buyer_name, kind: line.kind,
code: randomBytes(4).toString("hex").toUpperCase(),
priceCents: ticketPriceCents(show.price_cents, line.kind),
});
}
}
if (payment.amountCents !== row.total_cents) {
throw new Error(`Order ${row.token}: paid ${payment.amountCents} cents, expected ${row.total_cents}.`);
}
await client.query("COMMIT");
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
export async function cancelOrder(payment: Payment): Promise<void> {
const row = await findOrderByToken(payment.orderToken);
if (row === undefined) {
return;
}
const order = orderFromRow(row);
if (order.cancel(new Date()) === "cancelled") {
await saveOrderState(order);
}
}
The service no longer decides anything about states. It loads the row, asks the entity, saves what the entity says, and acts on the outcome. “Already paid” covers the duplicate webhook that the old if handled. “Too late” is committed too, because pay may have moved a held order whose hold ran out to cancelled.
The rest of markOrderPaid is unchanged on purpose. The email job is still queued before the tickets and outside the transaction, which Module 9 fixes. And nothing stops two webhooks from loading the same held order at once, which Module 7 fixes.
Last, the hold route asks the entity which orders take seats. In src/sales/routes/holds.ts, import orderFromRow and change the filter (two excerpts):
import { listOrdersForShow, orderFromRow } from "../db/orders.ts";
.filter((order) => orderFromRow(order).holdsSeats(now))
Delete the comment above const now, because the rule and its comment now live in holdsSeats. Run npm run check and npm test.
What you should see: npm run check prints no errors, and all 30 tests pass: the 25 from before and the five domain tests (an excerpt):
Order 768cf1edbcf38ac8a97d3928b716b8f6 was cancelled before payment pay_6172a930f7e233a3 came. Refund it by hand.
✔ a payment after the hold ran out leaves the order cancelled (12.989257ms)
✔ a failed payment after a received one leaves the order paid (13.455292ms)
...
ℹ tests 30
ℹ suites 0
ℹ pass 30
ℹ fail 0
The late payment leaves the order cancelled and logs it for a refund. The late failure leaves the paid order paid. Commit:
git add -A
git commit -m "Change an order's state only through the Order entity"
Step 4: Give “is this ticket sold?” one answer
Why: Figure 2 had four rules about one row. The hold route now asks the entity. The other three ask about status in SQL or in Door’s TypeScript.
What to do: find them:
grep -rnE "order_status|orders.status" src
What you should see:
src/sales/db/tickets.ts:25:export type TicketAtDoor = { code: string; kind: string; show_id: number; order_status: string };
src/sales/db/tickets.ts:29: `SELECT tickets.code, tickets.kind, tickets.show_id, orders.status AS order_status
src/sales/db/tickets.ts:42: WHERE tickets.show_id = $1 AND orders.status = 'paid' AND orders.cancelled_at IS NULL`,
src/platform/db/dashboard.ts:16: count(tickets.id) FILTER (WHERE orders.status = 'paid') AS tickets_sold,
src/platform/db/dashboard.ts:17: coalesce(sum(tickets.price_cents) FILTER (WHERE orders.status = 'paid'), 0) AS gross_cents,
src/platform/db/dashboard.ts:18: coalesce(sum(orders.quantity) FILTER (WHERE orders.status = 'held'), 0) AS seats_held,
src/door/routes/door.ts:24: if (ticket.order_status !== "paid") {
With orders_one_state, a row whose status is 'paid' has no cancelled_at. So the extra test in listSoldTicketPrices can go, and all three places agree that a ticket is sold when its order is paid. In src/sales/db/tickets.ts, change that line (an excerpt):
WHERE tickets.show_id = $1 AND orders.status = 'paid'`,
Door’s check compares a string, so a typo such as "payed" compiles. Give TicketAtDoor the status type (an excerpt, with the new import under the others):
import type { OrderStatus } from "../domain/order.ts";
export type TicketAtDoor = { code: string; kind: string; show_id: number; order_status: OrderStatus };
To see what that buys, change "paid" to "payed" in src/door/routes/door.ts and run npm run check.
What you should see:
src/door/routes/door.ts(24,7): error TS2367: This comparison appears to be unintentional because the types '"cancelled" | "held" | "paid"' and '"payed"' have no overlap.
With order_status: string, the same typo compiled with no error, and the door would have refused every ticket. Put "paid" back, run npm run check and npm test, and commit.
What you should see: no errors, and 30 tests pass.
git add -A
git commit -m "Count a ticket as sold when its order is paid"
Two copies of the order’s rules are left, on purpose. expireHolds cancels the holds that ran out with one SQL UPDATE, because loading every order to call cancel would cost one query per order. The dashboard counts 'held' rows as held seats, even for up to a minute after a hold ran out. Module 10 rebuilds the dashboard.
Step 5: Update the glossary and the README
Why: the glossary’s “Order” entry says what an order is, but not which states it has or who changes them.
What to do: in GLOSSARY.md, replace the body of the “Order” entry with this:
What one buyer asks for at one time: one show, a number of tickets of each
kind, and the price. Each kind of ticket with its number is one line of the
order. The order's token is its identity: the buyer's link and the payment
provider know the order by it.
An order is in one state at a time: held, paid or cancelled. It starts
held, and it takes seats until its hold runs out. It becomes paid when its
payment comes before the hold runs out, and then it stays paid. It becomes
cancelled when the hold runs out or the payment fails, and then it stays
cancelled. A payment that comes after the hold ran out is refunded by hand.
- Context: Sales.
- Code: the entity `Order` (`src/sales/domain/order.ts`), with `pay`,
`cancel` and `holdsSeats`. Table `sales.orders`, read and written through
`orderFromRow` 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/services/pricing.ts`).
- Do not say: tickets, for the lines of an order.
In the “Hold” entry, change the code line, because HOLD_MINUTES moved:
- Code: `sales.orders.hold_expires_at`; `HOLD_MINUTES` and `Order.hold`
(`src/sales/domain/order.ts`); `createHold`
(`src/sales/services/holds.ts`); the job `expire_holds`
(`src/sales/jobs/expire-holds.ts`).
In README.md, add a paragraph before the one about src/money/, and change 001 to 017 to 001 to 018 in the “Files” block:
Inside Sales, `src/sales/domain/order.ts` holds the `Order` entity: its
states (held, paid, cancelled) and the rules for moving between them. The
web app changes an order's state only through its methods. The job
`expire_holds` still cancels the holds that ran out with one `UPDATE`.
CONTEXT-MAP.md does not change, because no arrow between contexts moved. TicketAtDoor has the same fields, with a narrower type. The code figure gets a new folder inside Sales (Figure 5).
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Shows}, {Sales}, {Payouts} ..> money/ the shared kernel (#money)
Inside {Sales}: services/, db/ ..> domain/ NEW the Order entity: held, paid,
cancelled; it imports nothing
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 5: the arrows between contexts did not change; inside Sales, the order’s states now live in domain/.
Run the checks:
npm run check
npm test
What you should see: npm run check prints no errors, and npm test passes all 30 tests. The end of its output (from one run):
✔ a payment within the hold pays the order (1.839919ms)
✔ a payment after the hold ran out cancels the order (0.193432ms)
✔ a cancelled order is never paid later (0.208719ms)
✔ a failed payment never cancels a paid order (0.209574ms)
✔ a hold takes seats until it runs out (0.215044ms)
✔ a $12 ticket costs 1200, 960 for a student, 1700 as VIP (1.138921ms)
✔ one student ticket pays the booking fee (0.297413ms)
✔ four tickets or more pay no booking fee (0.198123ms)
✔ a context imports another context only through its # entry (9.163031ms)
ℹ tests 30
ℹ suites 0
ℹ pass 30
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
Commit:
git add -A
git commit -m "Describe the order's states in the glossary"
How a late payment works now
Follow the order from the scene through the new code (Figure 6):
- At 10:00 the buyer holds two seats.
createHoldcallsOrder.hold(token, now), which setsholdExpiresAtto 10:10.insertOrderchecks that the order is held and stores it withstatus'held'. - At 10:10 the worker’s
expireHoldssets the row to'cancelled'and fillscancelled_at. The constraint accepts the row, because it is in one state. - At 10:31 the provider’s webhook arrives. The layer from Module 4 turns it into a
Payment, and the route callsmarkOrderPaid. markOrderPaidloads the row, andorderFromRowreturns anOrderin the cancelled state.order.pay(10:31)reachescase "cancelled"and returns"too late". The state does not change.saveOrderStatewrites the same state back, the transaction commits, and the service logs that the payment needs a refund. No tickets and no email job are created.- The route answers 200, so the provider stops sending the webhook. The door, Payouts and the dashboard all read
'cancelled'.
10:00 (Buyer) --> [Web app] {Sales} services/holds.ts Order.hold --> held until 10:10
10:10 [Worker] {Sales} jobs/expire-holds.ts held --> cancelled [[sales.orders]]
10:31 [Payment provider] --> {Sales} acl/ ACL payment.succeeded --> Payment
{Sales} services/orders.ts findOrderByToken --> orderFromRow --> Order (cancelled)
{Sales} domain/order.ts pay(10:31) --> "too late"; the state stays cancelled
{Sales} db/orders.ts saveOrderState --> [[sales.orders]] status 'cancelled'
[Payment provider] <-- 200 log: "... Refund it by hand."
Figure 6: the late payment reaches the entity, which keeps the cancelled order cancelled.
If the worker had not run yet at 10:31, the row would still say 'held'. Then pay would find that holdExpiresAt had passed, move the order to cancelled itself, and return "too late" all the same. The answer no longer depends on when the worker ran.
Going deeper
A class, a union with functions, or flags
TinyTickets uses a class that holds a union. Figure 7 compares it with the other common ways to model an order’s state.
| Model of the state | What it buys | What it costs | Move to the next row when |
|---|---|---|---|
Booleans (paid, cancelled) |
nothing to learn | impossible combinations compile | two flags interact |
A status string, checked in services |
one column, one field | each service keeps its own copy of the rules | more than one place changes the status |
A class with a status union and methods |
the rules in one place; # fields keep callers out |
mapping code, because # fields are invisible to JSON.stringify |
states carry different data |
| A union with one member per state, in or out of a class | state-specific fields; never names missing cases |
more types; narrowing; row-to-union mapping | many states with much behavior each |
Figure 7: four models of an order’s state, from cheapest to most precise.
The last row can also have no class at all. A module exports type Order = Held | Paid | Cancelled and functions such as pay(order: Held): Paid. Then tsc refuses a call to pay with a cancelled order, and the caller must narrow first. TinyTickets keeps the class, because every webhook loads an order whose state is known only at run time, so the caller would narrow on every call anyway.
When each state has a lot of behavior, the State pattern gives each state its own object. Design Patterns in Plain Words, Module 4, builds it for an order with four statuses. With three states and two methods, a switch is shorter.
Where an identity comes from
TinyTickets makes the token in the application, before it saves the order. That is why Order.hold can create a complete order in memory, and why the domain tests need no database. An identity column, like id, exists only after the INSERT, so an entity with only that identity is incomplete until it is saved.
An application can also use a UUID. crypto.randomUUID() returns a random version 4 UUID (Node.js docs, crypto).
Node.js 26.1.0 added crypto.randomUUIDv7(), which returns a version 7 UUID from RFC 9562. Its top 48 bits are a Unix time in milliseconds, so values sort by the time they were made. The docs describe it as fit for a database key that sorts by time, and they warn that the time part is not guaranteed to increase strictly.
PostgreSQL 18 can make the same kind of value with uuidv7() (PostgreSQL 18 docs, UUID Functions). One run of each (your values will differ):
node -p "crypto.randomUUIDv7()"
docker exec tinytickets-db psql -U postgres -tAc "SELECT uuidv7()"
01a1f510-02a2-7bed-a179-2ad04f794baf
01a1f510-0328-7473-8975-ff88f8c083ec
TinyTickets keeps its hex token, because buyers and the provider already hold tokens in links and payments. Moving to a UUID would be a migration with no rule behind it.
Identities from outside, such as the provider’s payment ID, stay attributes of the order. They belong to another system, which can change its format. A brand, as in Module 5, would stop code from passing a payment ID where a token is expected. TinyTickets has not added one yet; the cost is one parse wherever a token enters.
What the authors meant
Evans keeps entities lean. In the Reference (p. 11), he asks that the class stay focused on identity and lifecycle, and he moves calculations into value objects and side-effect-free functions (p. 21). That is why Order holds only its token and its state, and the prices stay in pricing.ts.
Fowler’s “Value Object” page (2016) calls entities reference objects, which are compared by identity or by a key such as an order number. His “Anemic Domain Model” page does not name a case where an anemic model is fine. He says only that a domain model is not always the best tool.
The idea of one type per state comes from functional programming. Yaron Minsky’s “Effective ML Revisited” (2011) asks you to make illegal states unrepresentable. In his example, a record with optional fields becomes one type per state, joined in a variant. Scott Wlaschin’s “Designing with types: Making illegal states unrepresentable” (2013) credits Minsky and shows the same move in F#. TypeScript’s discriminated unions, added in TypeScript 2.0 (2016), make the same move possible in TypeScript.
Vaughn Vernon’s Implementing Domain-Driven Design (2013) gives entities a chapter of their own, chapter 5, according to the publisher’s table of contents.
What changed recently
- Node.js 26, the LTS line since October 2026, added
crypto.randomUUIDv7()in version 26.1.0, so an application can make a time-ordered ID with no package. - PostgreSQL 18, released on September 25, 2025, added
uuidv7(), anduuidv4()as another name forgen_random_uuid()(PostgreSQL 18 release notes). - Node.js runs
.tsfiles by stripping types, and Node.js 26.0.0 removed--experimental-transform-types(Node.js docs, TypeScript). Parameter properties andenumneed that transform, so entity code uses declared fields and string-literal unions instead.
When an entity is too much
Skip the class, the union and the factories for data that has no lifecycle rules. An organizer’s name and payout account, or the place of a show, change when someone edits them, and any value is allowed. A row type and an UPDATE say all there is to say, and an entity would add a file and mapping code for nothing.
The order earns it, because four files disagreed about its states, and a late webhook could break it. If only one function ever changed the status, a guard in that function would cost less. These limits are our judgment.
Check yourself
- Why is the token, and not
id, the order’s identity in the model?
Answer
The application makes the token before the INSERT, so an order has its identity from the moment Order.hold creates it. The buyer’s link and the payment provider know the order by its token. PostgreSQL assigns id only during the INSERT, so it stays the row’s key for sales.tickets.
- Why can
{ status: "paid", paidAt, cancelledAt }not be anOrderState, and what does theneverparameter ofassertNeveradd topayandcancel?
Answer
OrderState is a discriminated union. Once status is "paid", tsc checks the literal against the paid member, which has no cancelledAt, and reports TS2353. With a case for every state, the value in default has type never, and the call compiles. When someone adds a state, the value in default is that state, so tsc reports every switch that does not handle it, and names the state.
- What do
private constructorand#stateeach stop, and which one still works at run time?
Answer
private constructor makes tsc refuse new Order(...) outside the class, so hold and restore are the only ways in. Type stripping removes it, so plain JavaScript could still call new. #state is an ECMAScript private field, so JavaScript blocks access from outside the class at run time too, and JSON.stringify does not see it.
- The union already has a held state. Why does
paystill compareholdExpiresAtwithnow?
Answer
A type cannot know the time. A held order whose hold ran out is still 'held' in the row until the worker runs. Without the comparison, a payment at 10:31 would pay an order whose hold ended at 10:10 whenever the worker was late.
- The Module 5 code had an
Orderrow type and three functions that each wrotestatus. Why is that an anemic domain model, and when is a row with no methods the better choice?
Answer
The type was named after the domain but held only data, and the rules lived in the services, each with its own copy. That is Fowler’s anemic model. A row with no methods is the better choice for data with no lifecycle rules, such as an organizer’s profile.
Exercise: let tsc list what a refund touches
Leo asks for refunds: a paid order that he refunds gives its seats back and is never paid again. Before anyone builds the feature, find out what it touches.
Add a fourth member to OrderState in src/sales/domain/order.ts, { readonly status: "refunded"; readonly refundedAt: Date }, and run npm run check. Then make order.ts compile again, and add a refund(now) method with one domain test. Read the errors that remain outside order.ts, and undo everything at the end.
Solution
The new member gives four errors:
src/sales/db/orders.ts(17,46): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
src/sales/domain/order.ts(63,28): error TS2345: Argument of type '{ readonly status: "refunded"; readonly refundedAt: Date; }' is not assignable to parameter of type 'never'.
src/sales/domain/order.ts(79,28): error TS2345: Argument of type '{ readonly status: "refunded"; readonly refundedAt: Date; }' is not assignable to parameter of type 'never'.
src/sales/pages/shows.ts(43,6): error TS7053: Element implicitly has an 'any' type because expression of type '"cancelled" | "held" | "paid" | "refunded"' can't be used to index type '{ held: string; paid: string; cancelled: string; }'.
Property 'refunded' does not exist on type '{ held: string; paid: string; cancelled: string; }'.
The two never errors name the new state in pay and cancel. The switch in orderFromRow has no default, so tsc says only that the function can end without a return. holdsSeats gives no error: its || already returns false for a refunded order, which happens to be right.
In pay and in cancel, add a case before default, because a refunded order was paid once and changes no more:
case "refunded":
return "already paid";
Add the method after cancel:
// Leo refunds a paid order by hand. Its seats go back on sale.
refund(now: Date): boolean {
if (this.#state.status !== "paid") {
return false;
}
this.#state = { status: "refunded", refundedAt: now };
return true;
}
And add a test at the end of src/sales/domain/order.test.ts:
test("a refunded order takes no seats and is not paid again", () => {
const order = Order.hold("t6", tenOClock);
order.pay(minutesLater(2));
assert.equal(order.refund(minutesLater(30)), true);
assert.equal(order.holdsSeats(minutesLater(31)), false);
assert.equal(order.pay(minutesLater(32)), "already paid");
assert.equal(order.state.status, "refunded");
});
node --test src/sales/domain/order.test.ts now passes six tests, and npm run check reports only the errors in orders.ts and shows.ts. Those two need a refunded_at column, a new orders_one_state constraint and a sentence for the order page, so the feature is a migration and two files outside the entity. Undo the exercise:
git checkout src/sales/domain
Cheat sheet
Cheat sheet
- Entity: told apart by identity, not attributes; the same object while it changes. Not an ORM’s mapped class.
- Identity: made before the save when you can (the token, or
crypto.randomUUIDv7()); compare it, never===.- States: one union member per state, each with only its own data;
statusis the discriminant.- Exhaustiveness:
default: return assertNever(state)makestscname a state that aswitchforgot.- Ways in: a private constructor, plus
holdfor a new order andrestorefor a stored one.- Private fields:
#stateis private at run time too;JSON.stringifyskips it, so you map by hand.- Invariants: the type removes impossible shapes; methods refuse moves that depend on the past or the clock.
- Anemic model: rules in services, data in objects; cure it by moving the rules next to the data.
- Cost: more types, narrowing and mapping; skip it for data with no lifecycle rules.
Figure 8 is the whole module in one picture.
Create Order.hold(token, now) held, until now + 10 minutes
Load orderFromRow(row) --> Order.restore(token, state)
Change pay(now), cancel(now) return an outcome; never two states
Save saveOrderState(order) status, paid_at, cancelled_at
Database CHECK orders_one_state refuses a row in two states
Ask holdsSeats(now) paid, or held before holdExpiresAt
Figure 8: every change to an order’s state goes through the entity, and the database refuses a row in two states.
The order is now an entity with three states, and the webhooks change it only through pay and cancel. A late payment is logged for a refund instead of issuing tickets, and all 30 tests pass. Next, Module 7 turns to the seat rule, which still lives in the hold route, where two buyers can hold the last seat at the same moment.
Sources
- Eric Evans, Domain-Driven Design Reference: Definitions and Pattern Summaries, Domain Language, 2015 (CC BY 4.0). Entities (p. 11), Factories (p. 18), Side-Effect-Free Functions (p. 21), Assertions (p. 22).
- Martin Fowler, “Anemic Domain Model”, 2003, and “Value Object”, 2016.
- Yaron Minsky, “Effective ML Revisited”, Jane Street, 2011.
- Scott Wlaschin, “Designing with types: Making illegal states unrepresentable”, 2013.
- Vaughn Vernon, Implementing Domain-Driven Design, Addison-Wesley, 2013: table of contents.
- TypeScript: Narrowing, Classes, TypeScript 2.0 release notes (tagged unions,
never, private constructors), TypeScript 3.8 release notes (ECMAScript private fields). - Node.js documentation: crypto (
randomUUID,randomUUIDv7), TypeScript. - PostgreSQL 18 documentation: UUID Functions, release notes.