Leo found a digital wallet that took a smaller fee per ticket, and he wanted it on the Buy page by Friday. Maya opened the wallet’s SDK. It wanted dollars as text instead of cents, and it answered “SUCCEEDED” instead of “paid”. Every line of TinyTickets that took money expected the old shape.
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
You often can’t change the code you depend on, such as a company’s SDK (software development kit), the library it ships for calling its service. But you can wrap it in a small piece of your own code that changes one thing and leaves the rest alone. This module teaches four ways to wrap code, plus one short entry on groups.
After this module, you can:
- write an Adapter that makes an SDK fit your own interface, and test it with a plain fake
- put a Facade in front of a multi-step job (pay, save, notify), so that every route calls one function
- add retry or logging around a function with a Decorator, and choose the order of stacked wrappers
- put a Proxy in front of a slow service, and tell the four patterns apart by what each does to the interface
Set up the shared files
Use the folder from Module 1, with its fakes.ts. As in Module 1, every SDK in this module is a fake that prints a line instead of calling a real service. This module adds three new fakes: a wallet, a bank and the seat-map service.
Every example uses the types below, so save them as types.ts:
// Shared TinyTickets contracts used in this module
export type PaymentResult =
| { status: "paid"; chargeId: string }
| { status: "declined"; reason: string };
export interface PaymentProvider {
charge(amountCents: number): Promise<PaymentResult>;
}
export type Send = (to: string, text: string) => Promise<void>;
export interface SeatMapClient {
getSeatMap(showId: string, signal: AbortSignal): Promise<string[]>;
}
export type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";
export interface Order {
id: string;
showId: string;
buyerEmail: string;
quantity: number;
totalCents: number;
status: OrderStatus;
}
export interface OrderRepository {
findById(id: string): Promise<Order | undefined>;
save(order: Order): Promise<void>;
}
Each type here is a contract, a shape that both sides of a call agree on. PaymentResult is a discriminated union from Module 1, so its status field tells you which of the two cases you hold. Send has the same shape as Module 1’s Notify. OrderRepository stores orders, and Module 7 teaches it as the Repository pattern.
Save the wallet’s fake SDK as wallet-sdk.ts. It refuses payments over $100, so you can see a decline:
// Fake wallet SDK. It prints instead of calling a real service.
export type WalletPaymentRequest = {
amount: { value: string; currency: "USD" };
};
export type WalletPaymentResponse =
| { state: "SUCCEEDED"; paymentRef: string }
| { state: "REFUSED"; refusalCode: string };
export class WalletSdk {
constructor(merchantId: string) {
if (merchantId === "") throw new Error("WalletSdk needs a merchant id");
}
async createPayment(request: WalletPaymentRequest): Promise<WalletPaymentResponse> {
const { value, currency } = request.amount;
console.log(`[wallet] payment of ${value} ${currency}`);
if (Number(value) > 100) return { state: "REFUSED", refusalCode: "LIMIT_EXCEEDED" };
return { state: "SUCCEEDED", paymentRef: "wp_1" };
}
}
Adapter: make the wallet SDK fit PaymentProvider
The wallet SDK leaks into checkout
TinyTickets charges cards through PayClient from fakes.ts. To add the wallet, Maya added a branch to the checkout step that charges the buyer. Save it as adapter-before.ts:
import { PayClient } from "./fakes.ts";
import { WalletSdk } from "./wallet-sdk.ts";
type Method = "card" | "wallet";
const pay = new PayClient(process.env.PAY_KEY ?? "test-key");
const wallet = new WalletSdk(process.env.WALLET_MERCHANT ?? "merchant-7");
// The checkout step that charges the buyer
async function chargeOrder(method: Method, totalCents: number): Promise<string> {
if (method === "card") {
const charge = await pay.charge(totalCents);
return `paid ${charge.id}`;
}
// The wallet wants dollars as a string and answers with its own words
const response = await wallet.createPayment({
amount: { value: (totalCents / 100).toFixed(2), currency: "USD" },
});
if (response.state === "SUCCEEDED") return `paid ${response.paymentRef}`;
return `declined ${response.refusalCode}`;
}
console.log(await chargeOrder("card", 2550));
console.log(await chargeOrder("wallet", 2550));
console.log(await chargeOrder("wallet", 15000));
Output of npx tsx adapter-before.ts:
[pay] charged 2550 cents
paid ch_1
[wallet] payment of 25.50 USD
paid wp_1
[wallet] payment of 150.00 USD
declined LIMIT_EXCEEDED
toFixed(2) turns a number into text with two decimals, so 2550 cents becomes "25.50". The code works.
But chargeOrder now knows two SDKs, their units and their answers. The door-sale route and the nightly refund job also take money, so each one would need the same nine wallet lines. And a test of chargeOrder must create a real WalletSdk, or mock the import.
Pause and predict: the wallet’s shape is fixed, because another company owns it. Your
PaymentProvidershape is fixed too, because all of TinyTickets uses it. Where would you put the code that translates between them, and how many places should know the word “SUCCEEDED”?
A plug adapter for code
An Adapter is a small piece of code that makes something with the wrong shape fit the shape your code expects. The GoF book from Module 1 calls it a structural pattern, because it’s about how objects are wrapped. You need one when someone else wrote the code you depend on, so you can’t change its shape.
A travel plug adapter does the same job. Your laptop plug stays the same, the wall socket abroad stays the same, and the adapter between them changes only the shape. In the code, walletProvider sits between chargeOrder and WalletSdk in the same way. But a code adapter often converts values too, such as cents to dollars, while a plug adapter doesn’t change the electricity.
Figure 1 puts the two side by side. It also holds the legend for every figure in this course.
Travel plug adapter TinyTickets
+---------------------+ +------------------------------+
| (You) laptop plug | | [chargeOrder] |
+---------------------+ +------------------------------+
| | --> charge(cents)
+---------------------+ +------------------------------+
| plug adapter | | [walletProvider] NEW |
| changes the shape | | cents in, PaymentResult out |
+---------------------+ +------------------------------+
| | --> createPayment
+---------------------+ +------------------------------+
| wall socket abroad | | [WalletSdk] |
| you cannot change it| | dollars in, "SUCCEEDED" out |
+---------------------+ +------------------------------+
Legend, the same in every module
(Name) a person
[name] a module, function or class
[name] (I) an interface: a shape that other code must fit
A --> B A calls B
A ..> B A implements B: A has the shape that interface B asks for
A ==> B A creates B (with "new" or a factory function)
NEW a part that the change added
~ await ~ the caller waits here; Node.js serves other work meanwhile
Figure 1: the adapter sits between two shapes that you cannot change, as a plug adapter does.
With an adapter, you can change which SDK takes the money without touching the code that asks for money.
One adapter per SDK
Write one function per SDK. Each takes the SDK object and returns an object that fits PaymentProvider. Save providers.ts:
import type { PayClient } from "./fakes.ts";
import type { PaymentProvider } from "./types.ts";
import type { WalletSdk } from "./wallet-sdk.ts";
// Adapter: makes the card SDK fit PaymentProvider
export function cardProvider(pay: PayClient): PaymentProvider {
return {
async charge(amountCents) {
const charge = await pay.charge(amountCents);
return { status: "paid", chargeId: charge.id };
},
};
}
// Adapter: makes the wallet SDK fit PaymentProvider
export function walletProvider(wallet: WalletSdk): PaymentProvider {
return {
async charge(amountCents) {
const response = await wallet.createPayment({
amount: { value: (amountCents / 100).toFixed(2), currency: "USD" },
});
if (response.state === "SUCCEEDED") {
return { status: "paid", chargeId: response.paymentRef };
}
return { status: "declined", reason: response.refusalCode };
},
};
}
import type imports only a type, so the file doesn’t load the SDK’s code. The card SDK needs an adapter too, because PayClient answers { id } and not a PaymentResult. Now save adapter-after.ts:
import { PayClient } from "./fakes.ts";
import { cardProvider, walletProvider } from "./providers.ts";
import type { PaymentProvider } from "./types.ts";
import { WalletSdk } from "./wallet-sdk.ts";
type Method = "card" | "wallet";
const providers: Record<Method, PaymentProvider> = {
card: cardProvider(new PayClient(process.env.PAY_KEY ?? "test-key")),
wallet: walletProvider(new WalletSdk(process.env.WALLET_MERCHANT ?? "merchant-7")),
};
// The checkout step now knows one shape: PaymentProvider
async function chargeOrder(provider: PaymentProvider, totalCents: number): Promise<string> {
const result = await provider.charge(totalCents);
return result.status === "paid" ? `paid ${result.chargeId}` : `declined ${result.reason}`;
}
console.log(await chargeOrder(providers.card, 2550));
console.log(await chargeOrder(providers.wallet, 2550));
console.log(await chargeOrder(providers.wallet, 15000));
npx tsx adapter-after.ts prints the same six lines as the “before” version. But the word “SUCCEEDED” now appears in one file, providers.ts. Figure 2 shows the change in the arrows.
Before
[chargeOrder] --> [PayClient]
[chargeOrder] --> [WalletSdk] dollars, "SUCCEEDED", refusalCode
After
[adapter-after.ts] ==> [cardProvider] [walletProvider] NEW
[cardProvider] ..> [PaymentProvider] (I)
[walletProvider] ..> [PaymentProvider] (I)
[walletProvider] --> [WalletSdk]
[chargeOrder] --> [PaymentProvider] (I)
Figure 2: chargeOrder now calls one interface; only walletProvider knows the wallet’s words.
Figure 3 follows one wallet charge through the adapter.
1 [chargeOrder] --> [walletProvider] charge(2550)
2 [walletProvider] turns 2550 cents into "25.50"
3 [walletProvider] --> [WalletSdk] createPayment({ value: "25.50" })
~ await: the wallet answers; Node.js serves other requests ~
4 [WalletSdk] returns state "SUCCEEDED", ref "wp_1"
5 [walletProvider] returns status "paid", chargeId "wp_1"
6 [chargeOrder] returns "paid wp_1"
Figure 3: the adapter translates twice, once on the way in and once on the way out.
Test the adapter with a plain fake
The adapter has real logic, a unit change and a mapping of answers, so test it with a fake wallet. Save providers.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { walletProvider } from "./providers.ts";
import type { WalletPaymentRequest, WalletPaymentResponse } from "./wallet-sdk.ts";
test("walletProvider sends dollars and maps a refusal to declined", async () => {
const requests: WalletPaymentRequest[] = [];
const fakeWallet = {
async createPayment(request: WalletPaymentRequest): Promise<WalletPaymentResponse> {
requests.push(request);
return { state: "REFUSED", refusalCode: "LIMIT_EXCEEDED" };
},
};
const result = await walletProvider(fakeWallet).charge(2550);
assert.deepEqual(requests, [{ amount: { value: "25.50", currency: "USD" } }]);
assert.deepEqual(result, { status: "declined", reason: "LIMIT_EXCEEDED" });
});
Run it with npx tsx --test providers.test.ts:
✔ walletProvider sends dollars and maps a refusal to declined (0.660292ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
fakeWallet is a plain object, but walletProvider asks for a WalletSdk. It still fits because of structural typing from Module 1, where TypeScript checks an object’s shape and not its class. The object has the one method that a WalletSdk has.
The “before” chargeOrder couldn’t be tested this way, because it created its own WalletSdk at the top of the file. Now you can also test the checkout code with a fake PaymentProvider that never touches an SDK.
Note: A private field is a field that only code inside the class can read, marked with
privateor with#before its name. A class with one accepts only real instances, as the handbook’s type compatibility rules explain.WalletSdkhas none, so the fake fits. If an SDK class has one, give the adapter a small interface with only the method it calls.
Add a bank transfer with one new adapter
Leo’s next request is bank transfers for large group orders. The bank’s fake SDK, bank-sdk.ts, has yet another shape:
// Fake bank-transfer SDK. It prints instead of calling a real service.
export class BankApi {
async requestTransfer(cents: number, memo: string): Promise<{ ok: boolean; transferId: string }> {
console.log(`[bank] transfer of ${cents} cents, memo "${memo}"`);
return { ok: true, transferId: "bt_1" };
}
}
You write one new adapter, bank-provider.ts:
import type { BankApi } from "./bank-sdk.ts";
import type { PaymentProvider } from "./types.ts";
// Adapter: makes the bank SDK fit PaymentProvider
export function bankTransferProvider(bank: BankApi): PaymentProvider {
return {
async charge(amountCents) {
const reply = await bank.requestTransfer(amountCents, "TinyTickets order");
if (reply.ok) return { status: "paid", chargeId: reply.transferId };
return { status: "declined", reason: "bank refused the transfer" };
},
};
}
Then copy adapter-after.ts to adapter-next.ts. In the copy, "bank" joins Method, the two bank files are imported, one entry joins the map and one call is added at the end. This excerpt shows only those lines:
// excerpt: the lines of adapter-next.ts that differ from adapter-after.ts
import { BankApi } from "./bank-sdk.ts";
import { bankTransferProvider } from "./bank-provider.ts";
type Method = "card" | "wallet" | "bank";
bank: bankTransferProvider(new BankApi()),
console.log(await chargeOrder(providers.bank, 6000));
The output is the six lines from before, plus two:
[bank] transfer of 6000 cents, memo "TinyTickets order"
paid bt_1
chargeOrder didn’t change. If you forget the map entry, tsc reports that the property bank is missing, as with Record in Module 1.
When an Adapter is worth its cost
Use an Adapter when:
- you import an SDK type, such as
WalletPaymentResponse, into business logic - the same conversion (cents to dollars, “SUCCEEDED” to “paid”) appears in two places
- you want to switch vendors later, or a test needs a fake in place of the SDK
Skip it when:
- the shapes already match. Structural typing makes the SDK fit with no code at all.
- one call site uses the SDK once, in a script. Call it directly and keep the translation next to the call.
- the code with the wrong shape is your own. Change it to the right shape instead of wrapping it.
Each SDK gets one more file and one more name. The adapter also hides whatever doesn’t fit the interface. If the wallet can refund a payment, PaymentProvider can’t show it, so you must grow the interface for every provider or call the SDK directly.
When the SDK releases a new version, the adapter is the one file to update, but someone must remember to do it. Stack traces also gain one line per adapter.
Exercise: adapt an SMS SDK
A new SMS vendor’s fake SDK has this shape:
// Fake SMS SDK with its own shape. It prints instead of calling a real service.
export class TextBlast {
async sendMessage(message: { phone: string; body: string }): Promise<{ queued: boolean }> {
console.log(`[sms] to ${message.phone}: ${message.body}`);
return { queued: message.phone.startsWith("+") };
}
}
Save it as text-blast.ts. Write textBlastSend(client: TextBlast): Send, which throws an error when the message wasn’t queued.
Answer
text-blast-send.ts:
import { TextBlast } from "./text-blast.ts";
import type { Send } from "./types.ts";
export function textBlastSend(client: TextBlast): Send {
return async (to, text) => {
const reply = await client.sendMessage({ phone: to, body: text });
if (!reply.queued) throw new Error(`SMS to ${to} was not queued`);
};
}
const send = textBlastSend(new TextBlast());
await send("+15550101", "Your tickets for Songs of Spring");
try {
await send("5550101", "Your tickets for Songs of Spring");
} catch (err: unknown) {
if (err instanceof Error) console.log(err.message);
}
Output:
[sms] to +15550101: Your tickets for Songs of Spring
[sms] to 5550101: Your tickets for Songs of Spring
SMS to 5550101 was not queued
The adapter turns the vendor’s { queued: false } into a thrown error, because a Send signals failure by rejecting its promise. So callers of Send never see the word queued.
Facade: one call for the whole checkout
Two routes repeat the same four steps
Every online order runs the same steps: work out the total, charge the buyer, save the order, email the receipt. Leo’s next request is door sales. At the door, he types the buyer’s email and the number of tickets into an admin page, and the same steps run.
Maya copied the online steps into the new route. Save facade-before.ts:
import { MailClient, PayClient } from "./fakes.ts";
import type { Order } from "./types.ts";
const pay = new PayClient(process.env.PAY_KEY ?? "test-key");
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const saved = new Map<string, Order>();
// POST /checkout: a buyer pays online
async function onlineCheckout(buyerEmail: string, quantity: number): Promise<Order> {
const totalCents = 1200 * quantity + (quantity >= 4 ? 0 : 150);
const charge = await pay.charge(totalCents);
const id = `order-${saved.size + 1}`;
const order: Order = { id, showId: "spring", buyerEmail, quantity, totalCents, status: "paid" };
saved.set(id, order);
console.log(`[db] saved ${id} (paid)`);
await mail.send(buyerEmail, `Your tickets for Songs of Spring, receipt ${charge.id}`);
return order;
}
// POST /admin/door-sale: Leo sells tickets at the door (copied from above)
async function doorSale(buyerEmail: string, quantity: number): Promise<Order> {
const totalCents = 1200 * quantity + (quantity >= 4 ? 0 : 150);
const charge = await pay.charge(totalCents);
const id = `order-${saved.size + 1}`;
const order: Order = { id, showId: "spring", buyerEmail, quantity, totalCents, status: "paid" };
saved.set(id, order);
console.log(`[db] saved ${id} (paid)`);
await mail.send(buyerEmail, `Your tickets for Songs of Spring, receipt ${charge.id}`);
return order;
}
await onlineCheckout("ana@example.com", 2);
await doorSale("ben@example.com", 4);
Output:
[pay] charged 2550 cents
[db] saved order-1 (paid)
[mail] to ana@example.com: Your tickets for Songs of Spring, receipt ch_1
[pay] charged 4800 cents
[db] saved order-2 (paid)
[mail] to ben@example.com: Your tickets for Songs of Spring, receipt ch_1
The [db] line stands in for a database write. Both routes work, but each one knows five things:
- the price rule
- the payment SDK
- the storage
- the mail SDK
- the order of the four steps
So the next change to any step, such as a declined payment, must be made twice, and the two copies will slowly become different. Neither route can be tested without the real clients.
Pause and predict: what do the two routes need to know, and what could they stop knowing? Sketch one function that both could call.
A front desk for your services
A Facade is one simple entry point in front of several parts that must be used together, in the right order. It’s another GoF structural pattern. The parts stay as they are, and callers talk to the facade instead.
A hotel front desk works this way. You ask for a late checkout, and the desk talks to housekeeping and billing for you. In the code, both routes call placeOrder, and placeOrder calls payments, orders and send. But other code can still call the parts directly, while a hotel may stop guests from calling housekeeping.
Figure 4 shows the desk next to the code.
Hotel TinyTickets
(Guest) [onlineCheckout] [doorSale]
| | |
v v v
+--------------+ +-------------------------------+
| front desk | | [placeOrder] NEW |
+--------------+ +-------------------------------+
| | | | |
v v v v v
housekeeping billing [payments] [orders] [send]
Figure 4: callers talk to one desk, and the desk talks to the parts behind it.
With a facade, you can change the steps of an order, or their order, in one place, without touching any route.
One function for price, payment, storage and receipt
The facade is a factory function from Module 2, a function that builds and returns another function or object. makePlaceOrder takes the parts and returns the placeOrder function. Save place-order.ts:
import type { Order, OrderRepository, PaymentProvider, Send } from "./types.ts";
export type CheckoutDeps = { payments: PaymentProvider; orders: OrderRepository; send: Send };
export type OrderInput = { buyerEmail: string; quantity: number };
export type PlaceOrder = (input: OrderInput) => Promise<Order>;
// Facade: one call for price, payment, storage and receipt
export function makePlaceOrder(deps: CheckoutDeps): PlaceOrder {
let count = 0;
return async ({ buyerEmail, quantity }) => {
const totalCents = 1200 * quantity + (quantity >= 4 ? 0 : 150);
const result = await deps.payments.charge(totalCents);
if (result.status === "declined") throw new Error(`declined: ${result.reason}`);
count++;
const id = `order-${count}`;
const order: Order = { id, showId: "spring", buyerEmail, quantity, totalCents, status: "paid" };
await deps.orders.save(order);
await deps.send(buyerEmail, `Your tickets for Songs of Spring, receipt ${result.chargeId}`);
return order;
};
}
count lives in the closure, so each placeOrder numbers its own orders. The card provider never declines, so the throw never runs here. It’s there because a PaymentProvider may answer “declined”, and the “before” code had no answer for that.
You also need an in-memory OrderRepository. Save memory-orders.ts:
import type { Order, OrderRepository } from "./types.ts";
// An in-memory OrderRepository. It prints instead of writing to a database.
export function memoryOrders(): OrderRepository {
const rows = new Map<string, Order>();
return {
async findById(id) {
return rows.get(id);
},
async save(order) {
rows.set(order.id, order);
console.log(`[db] saved ${order.id} (${order.status})`);
},
};
}
Now save the routes as facade-after.ts. It reuses cardProvider from the Adapter section:
import { MailClient, PayClient } from "./fakes.ts";
import { memoryOrders } from "./memory-orders.ts";
import { makePlaceOrder, type OrderInput } from "./place-order.ts";
import { cardProvider } from "./providers.ts";
import type { Order } from "./types.ts";
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const placeOrder = makePlaceOrder({
payments: cardProvider(new PayClient(process.env.PAY_KEY ?? "test-key")),
orders: memoryOrders(),
send: (to, text) => mail.send(to, text),
});
// POST /checkout: a buyer pays online
async function onlineCheckout(input: OrderInput): Promise<Order> {
return placeOrder(input);
}
// POST /admin/door-sale: Leo sells tickets at the door
async function doorSale(input: OrderInput): Promise<Order> {
return placeOrder(input);
}
await onlineCheckout({ buyerEmail: "ana@example.com", quantity: 2 });
await doorSale({ buyerEmail: "ben@example.com", quantity: 4 });
npx tsx facade-after.ts prints the same six lines. In the real app, each route also reads req.body and sends the response. That part differs between the routes, so it stays in them. Figure 5 shows the structure before and after.
Before
[onlineCheckout] --> [PayClient] [Map] [MailClient]
[doorSale] --> [PayClient] [Map] [MailClient] copied steps
After
[onlineCheckout] --> [placeOrder]
[doorSale] --> [placeOrder]
[facade-after.ts] ==> [placeOrder] NEW
[placeOrder] --> [PaymentProvider] (I) [OrderRepository] (I) [Send]
Figure 5: both routes call one facade, and only the facade knows the steps and their order.
Test the order of the steps
The order of the steps is the facade’s job, so the test checks the order. Save place-order.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { makePlaceOrder } from "./place-order.ts";
test("placeOrder charges, then saves, then sends the receipt", async () => {
const steps: string[] = [];
const placeOrder = makePlaceOrder({
payments: {
async charge(amountCents) {
steps.push(`charge ${amountCents}`);
return { status: "paid", chargeId: "ch_test" };
},
},
orders: {
async findById() { return undefined; },
async save(order) { steps.push(`save ${order.id} ${order.status}`); },
},
send: async (to) => { steps.push(`send ${to}`); },
});
await placeOrder({ buyerEmail: "ana@example.com", quantity: 2 });
assert.deepEqual(steps, ["charge 2550", "save order-1 paid", "send ana@example.com"]);
});
Output of npx tsx --test place-order.test.ts:
✔ placeOrder charges, then saves, then sends the receipt (0.6985ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
The three fakes are plain objects and functions. The “before” routes couldn’t be tested this way, because they used three clients created at the top of the file. A test had no way to hand in its own.
Save declined orders without touching the routes
Leo wants declined payments on record, so he can call the buyer back. A declined order is saved as "cancelled", and no receipt goes out. In place-order.ts, replace the body of the returned function with the excerpt below, and keep the rest of the file:
// excerpt: the new body of the function that makePlaceOrder returns
const totalCents = 1200 * quantity + (quantity >= 4 ? 0 : 150);
const result = await deps.payments.charge(totalCents);
count++;
const id = `order-${count}`;
const status = result.status === "paid" ? "paid" : "cancelled";
const order: Order = { id, showId: "spring", buyerEmail, quantity, totalCents, status };
await deps.orders.save(order);
if (result.status === "paid") {
await deps.send(buyerEmail, `Your tickets for Songs of Spring, receipt ${result.chargeId}`);
}
return order;
The throw is gone, status depends on the result, and the receipt goes out only when paid. Wired with walletProvider, a second order of 10 tickets (12,000 cents) is refused, and that order prints:
[wallet] payment of 120.00 USD
[db] saved order-2 (cancelled)
The two routes didn’t change. In the “before” code, this change was two edits that had to match.
When a Facade is worth its cost
Use a Facade when:
- two or more callers repeat the same steps across the same services
- callers must know a fixed order, such as “save before you send”
- a route handler imports three or more SDKs or clients
Skip it when:
- there is one caller and three lines. A plain function is already a facade in its smallest form, so it needs no name or file of its own.
- the facade starts collecting unrelated jobs. A
TicketsFacadewith 20 methods hides nothing, so split it by job.
The facade adds one more layer to read. “Go to definition” on placeOrder opens the facade, and you open a second file to see the steps.
A facade that keeps growing becomes a god object, a single object that knows everything. And a caller with an unusual need, such as a door sale with no receipt, now needs an option on the facade or a direct call to the parts.
Exercise: test the declined path
Write a test for the new version of placeOrder: a declined payment saves a cancelled order and sends nothing.
Answer
declined.test.ts, run against the updated place-order.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { makePlaceOrder } from "./place-order.ts";
test("a declined payment saves a cancelled order and sends nothing", async () => {
const steps: string[] = [];
const placeOrder = makePlaceOrder({
payments: { async charge() { return { status: "declined", reason: "LIMIT_EXCEEDED" }; } },
orders: {
async findById() { return undefined; },
async save(order) { steps.push(`save ${order.status}`); },
},
send: async (to) => { steps.push(`send ${to}`); },
});
const order = await placeOrder({ buyerEmail: "ben@example.com", quantity: 10 });
assert.equal(order.status, "cancelled");
assert.deepEqual(steps, ["save cancelled"]);
});
It passes with ℹ pass 1. Checking steps proves two things, that the order was saved and that send was never called.
Decorator: add behavior around a function
Retry and logging grow inside the send code
On sale night, the SMS service timed out on the first try and worked on the second. So Leo asked for two things. A failed ticket text should be tried up to three times, and each try should be logged. Maya wrote both into the function that sends tickets. Save decorator-before.ts:
import { SmsClient } from "./fakes.ts";
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
let calls = 0;
// The SMS service fails on the first call, as it did on sale night
async function smsSend(to: string, text: string): Promise<void> {
calls++;
if (calls === 1) throw new Error("SMS service timed out");
await sms.send(to, text);
}
// Retry and logging, written into the function that sends tickets
async function sendTicketText(to: string, text: string): Promise<void> {
for (let attempt = 1; ; attempt++) {
console.log(`[log] send to ${to}`);
try {
await smsSend(to, text);
return;
} catch (err: unknown) {
if (attempt >= 3) throw err;
const reason = err instanceof Error ? err.message : String(err);
console.log(`[retry] attempt ${attempt} failed: ${reason}`);
}
}
}
await sendTicketText("+15550100", "Your tickets for Songs of Spring");
Output:
[log] send to +15550100
[retry] attempt 1 failed: SMS service timed out
[log] send to +15550100
[sms] to +15550100: Your tickets for Songs of Spring
smsSend fails once on purpose, so you can see a retry.
But the retry loop, the log line and the SMS call are mixed in one function. Email receipts need the same retry next week, and push the week after, so each one means a copy of the loop. A test of the retry logic must also go through SmsClient.
Pause and predict: retry does not care whether the message goes by SMS or email. How could you write it once and put it around any
Send? If you also write logging once, which one goes on the outside?
A phone case for a function
A Decorator wraps an object or function with another one of the same shape, and adds behavior before or after the call. Callers can’t tell the difference, so you can stack several decorators. It’s the third GoF structural pattern in this module.
Note: The Decorator pattern and TypeScript’s
@decoratorsyntax are different things, as Module 1 showed. The pattern wraps an object to add behavior, and the syntax is a language feature.
A phone case works the same way. The case fits around the phone, the buttons press through, and you can add a strap on top. In the code, withLogging wraps smsSend, withRetry wraps both, and every layer is a Send. But a case and a strap work in either order, while the order of decorators changes the result.
Figure 6 puts the layers side by side.
Phone in layers A Send in layers
+------------------------+ +-------------------------------+
| strap | | [withRetry] NEW |
| +--------------------+ | | +---------------------------+ |
| | case | | | | [withLogging] NEW | |
| | +----------------+ | | | | +-----------------------+ | |
| | | phone | | | | | | [smsSend] | | |
| | +----------------+ | | | | +-----------------------+ | |
| +--------------------+ | | +---------------------------+ |
+------------------------+ +-------------------------------+
the buttons press through every layer is a Send
Figure 6: each layer has the same shape as what it wraps, so layers stack.
With decorators, you can change how a call runs, with retries, logs or timing, without touching the caller or the code that does the work.
withRetry and withLogging
Module 1 wrote withLogging for Notify. Here are both wrappers for Send. Save send-wrappers.ts:
import type { Send } from "./types.ts";
// Decorator: same Send shape, plus retries
export function withRetry(send: Send, attempts: number): Send {
return async (to, text) => {
for (let attempt = 1; ; attempt++) {
try {
await send(to, text);
return;
} catch (err: unknown) {
if (attempt >= attempts) throw err;
const reason = err instanceof Error ? err.message : String(err);
console.log(`[retry] attempt ${attempt} failed: ${reason}`);
}
}
};
}
// Decorator: same Send shape, plus a log line
export function withLogging(send: Send): Send {
return async (to, text) => {
console.log(`[log] send to ${to}`);
await send(to, text);
};
}
withRetry tries again at once, with no wait between tries. Module 9 adds waits that grow between tries. Now save decorator-after.ts:
import { SmsClient } from "./fakes.ts";
import { withLogging, withRetry } from "./send-wrappers.ts";
import type { Send } from "./types.ts";
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
let calls = 0;
// The SMS service fails on the first call, as it did on sale night
const smsSend: Send = async (to, text) => {
calls++;
if (calls === 1) throw new Error("SMS service timed out");
await sms.send(to, text);
};
// Logging inside retry: every attempt is logged
const sendTicketText = withRetry(withLogging(smsSend), 3);
await sendTicketText("+15550100", "Your tickets for Songs of Spring");
npx tsx decorator-after.ts prints the same four lines. Now smsSend does one job, and each wrapper does one job. Figure 7 shows the structure before and after.
Before
[sendTicketText] --> [smsSend] retry loop and log line inside
After
[decorator-after.ts] ==> [withRetry] ==> [withLogging] NEW
[withRetry] --> [withLogging] --> [smsSend]
[withRetry] ..> [Send] (I) [withLogging] ..> [Send] (I)
[smsSend] ..> [Send] (I)
Figure 7: three small functions of the same shape replace one mixed function.
Send is a function type and not an interface, but it plays the same part, so Figure 7 marks it (I).
The order of stacked wrappers
withRetry(withLogging(smsSend), 3) logs every try. withLogging(withRetry(smsSend, 3)) logs once, before all the tries. Figure 8 follows the first version, where the first try fails.
1 [caller] --> [withRetry] send("+15550100", text), attempt 1
2 [withRetry] --> [withLogging] prints "[log] send to +15550100"
3 [withLogging] --> [smsSend] fails: "SMS service timed out"
~ await: the rejection travels back out to withRetry ~
4 [withRetry] prints "[retry] attempt 1 failed"
5 [withRetry] --> [withLogging] attempt 2, prints "[log] ..." again
6 [withLogging] --> [smsSend] sends the text
~ await ~
7 [withRetry] returns the caller's promise resolves
Figure 8: with logging inside retry, each attempt is logged; swap them and only the first call is logged.
Rule: A wrapper outside
withRetryruns once per call; a wrapper inside it runs once per attempt.
Test that retry gives up
Save send-wrappers.test.ts. It checks the hardest part of retry, which is giving up.
import { test } from "node:test";
import assert from "node:assert/strict";
import { withRetry } from "./send-wrappers.ts";
import type { Send } from "./types.ts";
test("withRetry tries again, then gives up after the last attempt", async () => {
let calls = 0;
const alwaysFails: Send = async () => {
calls++;
throw new Error("SMS service timed out");
};
await assert.rejects(withRetry(alwaysFails, 3)("+15550100", "hi"), /timed out/);
assert.equal(calls, 3);
});
Output of npx tsx --test send-wrappers.test.ts:
[retry] attempt 1 failed: SMS service timed out
[retry] attempt 2 failed: SMS service timed out
✔ withRetry tries again, then gives up after the last attempt (0.837917ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
assert.rejects passes when the promise rejects with an error that matches the pattern. The fake is a three-line function. In the “before” code, the loop called the real smsSend, so a test couldn’t force a failure without mocking.
Retry email with no copied loop
Email receipts need the same retry. Save decorator-next.ts, which adds three lines marked NEW:
import { MailClient, SmsClient } from "./fakes.ts";
import { withLogging, withRetry } from "./send-wrappers.ts";
import type { Send } from "./types.ts";
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
let calls = 0;
// The SMS service fails on the first call, as it did on sale night
const smsSend: Send = async (to, text) => {
calls++;
if (calls === 1) throw new Error("SMS service timed out");
await sms.send(to, text);
};
const mailSend: Send = (to, subject) => mail.send(to, subject); // NEW
const sendTicketText = withRetry(withLogging(smsSend), 3);
const sendTicketEmail = withRetry(withLogging(mailSend), 3); // NEW
await sendTicketText("+15550100", "Your tickets for Songs of Spring");
await sendTicketEmail("ana@example.com", "Your tickets for Songs of Spring"); // NEW
Pause and predict: the SMS send fails once, and the email send works on the first try. How many
[log]lines and how many[retry]lines does this print?
Output:
[log] send to +15550100
[retry] attempt 1 failed: SMS service timed out
[log] send to +15550100
[sms] to +15550100: Your tickets for Songs of Spring
[log] send to ana@example.com
[mail] to ana@example.com: Your tickets for Songs of Spring
It prints three [log] lines and one [retry] line. The SMS send is logged twice, because logging sits inside retry and runs on each attempt. The email send is logged once, because its first attempt works.
No loop was copied. The other edits were the MailClient import and the line that creates mail.
When a Decorator is worth its cost
Use a Decorator when:
- the same retry, logging, timing or caching code is copied around several calls
- you want a behavior on for one caller and off for another, such as retries in production and none in tests
- you can’t edit the wrapped code, because it’s an SDK
Skip it when:
- only one function needs the behavior, and it’s your own. Write the two extra lines inside it.
- the behavior changes what the call means, not how it runs. A wrapper that turns a failed charge into “paid” without telling anyone is a bug.
Every layer adds one more promise, one more await and one more line in the stack trace. Anonymous arrow functions also appear there with no name. The order of layers is now a decision that readers must check, as Figure 8 shows. And retrying a call with side effects, such as a charge, can repeat the side effect; Module 9 covers when a retry is safe.
Exercise: decorate a PaymentProvider
A decorator can also wrap an object with methods. Write logCharges(inner: PaymentProvider): PaymentProvider. It logs the amount before each charge and the status after it.
Answer
log-charges.ts:
import { PayClient } from "./fakes.ts";
import { cardProvider } from "./providers.ts";
import type { PaymentProvider } from "./types.ts";
function logCharges(inner: PaymentProvider): PaymentProvider {
return {
async charge(amountCents) {
console.log(`[log] charge ${amountCents} cents`);
const result = await inner.charge(amountCents);
console.log(`[log] result ${result.status}`);
return result;
},
};
}
await logCharges(cardProvider(new PayClient("test-key"))).charge(2550);
Output:
[log] charge 2550 cents
[pay] charged 2550 cents
[log] result paid
The decorator must write out every method of the interface, even the ones it doesn’t change. PaymentProvider has one method, so that’s easy.
Proxy: stand in front of the slow seat-map service
A cache written into a route handler
The seat-map service at https://seats.tinytickets.example takes a long time to answer. At 10:00 on a sale day, every buyer opens the same seat map. So Maya added a five-second cache inside the route handler. First, save the fake client as seat-map-fake.ts:
import { setTimeout as sleep } from "node:timers/promises";
import type { SeatMapClient } from "./types.ts";
// Fake seat-map SDK. It prints instead of calling the real service.
export class SeatMapHttpClient implements SeatMapClient {
readonly baseUrl: string;
constructor(baseUrl: string) {
console.log(`[seats] connecting to ${baseUrl}`);
this.baseUrl = baseUrl;
}
async getSeatMap(showId: string, signal: AbortSignal): Promise<string[]> {
console.log(`[seats] GET ${this.baseUrl}/shows/${showId}/seats`);
await sleep(50, undefined, { signal }); // the slow part
return [`${showId}-A1`, `${showId}-A2`];
}
}
Then save proxy-before.ts:
import { SeatMapHttpClient } from "./seat-map-fake.ts";
const client = new SeatMapHttpClient("https://seats.tinytickets.example");
const cache = new Map<string, { seats: string[]; expiresAt: number }>();
// GET /shows/:id/seats, with a cache written into the handler
async function seatsPage(showId: string): Promise<string> {
let seats: string[];
const hit = cache.get(showId);
if (hit !== undefined && hit.expiresAt > Date.now()) {
seats = hit.seats;
} else {
seats = await client.getSeatMap(showId, AbortSignal.timeout(2000));
cache.set(showId, { seats, expiresAt: Date.now() + 5000 });
}
return `${showId}: ${seats.length} free seats`;
}
for (const showId of ["spring", "spring", "summer", "spring"]) {
console.log(await seatsPage(showId));
}
Output:
[seats] connecting to https://seats.tinytickets.example
[seats] GET https://seats.tinytickets.example/shows/spring/seats
spring: 2 free seats
spring: 2 free seats
[seats] GET https://seats.tinytickets.example/shows/summer/seats
summer: 2 free seats
spring: 2 free seats
AbortSignal.timeout(2000), from Module 1, stops the call after two seconds. Four page views made two calls to the service.
Then Leo asked for a seat picker on the checkout page, which reads the same seat map. If Maya copies the cache, two caches can disagree. If she skips it, the picker calls the slow service on every view. The cache code also hides what the handler does.
Pause and predict: the page wants a
SeatMapClient. Could you hand it an object that looks like aSeatMapClientbut answers from a cache when it can? Who would hold the cache?
An assistant who answers for the manager
A Proxy is a stand-in with the same interface as the real object, and it decides whether, when and how the real object is called. It’s the fourth GoF structural pattern in this module. A caching proxy is one kind, which answers repeat requests from memory.
An assistant who answers a busy manager’s phone works this way. You dial the same number, and the assistant answers common questions from notes taken this morning. Anything else goes through to the manager. In the code, seatsPage calls cachedSeatMap, which calls SeatMapHttpClient only when it has no fresh answer.
But an assistant can tell when notes are too old to trust, while the code trusts its cache for a fixed time. Figure 9 shows both.
Office TinyTickets
(Caller) [seatsPage]
| dials the same number | --> getSeatMap("spring")
v v
+--------------------------+ +------------------------------+
| assistant | | [cachedSeatMap] NEW |
| answers from today's | | answers from the cache |
| notes when it can | | when the entry is fresh |
+--------------------------+ +------------------------------+
| only when needed | --> only on a miss
v v
+--------------------------+ +------------------------------+
| busy manager | | [SeatMapHttpClient] |
+--------------------------+ +------------------------------+
Figure 9: callers use the same number or interface; the stand-in decides when to call through.
With a proxy, you can change when and how often the real service is called without touching the callers or the service.
A caching proxy for the seat map
Save cached-seat-map.ts:
import type { SeatMapClient } from "./types.ts";
// Proxy: same SeatMapClient shape; it decides whether to call the real one
export function cachedSeatMap(
client: SeatMapClient,
ttlMs: number,
now: () => number = Date.now,
): SeatMapClient {
const cache = new Map<string, { seats: string[]; expiresAt: number }>();
return {
async getSeatMap(showId, signal) {
const hit = cache.get(showId);
if (hit !== undefined && hit.expiresAt > now()) return [...hit.seats];
const seats = await client.getSeatMap(showId, signal);
cache.set(showId, { seats, expiresAt: now() + ttlMs });
return [...seats];
},
};
}
TTL, short for “time to live”, is how long a cache entry stays valid. now is the clock, with Date.now as the default, so a test can pass a fake clock. [...hit.seats] returns a copy of the array, so a caller that changes its copy can’t change the cache. On a miss, the signal goes to the real client, so the timeout still works.
Now save proxy-after.ts:
import { cachedSeatMap } from "./cached-seat-map.ts";
import { SeatMapHttpClient } from "./seat-map-fake.ts";
import type { SeatMapClient } from "./types.ts";
const seatMap = cachedSeatMap(new SeatMapHttpClient("https://seats.tinytickets.example"), 5000);
// GET /shows/:id/seats: no cache code here any more
async function seatsPage(seatMap: SeatMapClient, showId: string): Promise<string> {
const seats = await seatMap.getSeatMap(showId, AbortSignal.timeout(2000));
return `${showId}: ${seats.length} free seats`;
}
for (const showId of ["spring", "spring", "summer", "spring"]) {
console.log(await seatsPage(seatMap, showId));
}
npx tsx proxy-after.ts prints the same seven lines. The seat picker gets the same seatMap object, so it shares the cache with no new code. Figure 10 shows the structure.
Before
[seatsPage] --> [SeatMapHttpClient] cache Map inside the handler
After
[proxy-after.ts] ==> [SeatMapHttpClient]
[proxy-after.ts] ==> [cachedSeatMap] NEW
[cachedSeatMap] ..> [SeatMapClient] (I)
[SeatMapHttpClient] ..> [SeatMapClient] (I)
[seatsPage] --> [SeatMapClient] (I)
[cachedSeatMap] --> [SeatMapHttpClient] only on a miss
Figure 10: the proxy and the real client fit the same interface, so the handler can’t tell them apart.
Test the cache with a fake clock
Save cached-seat-map.test.ts. The fake clock makes time a variable you set:
import { test } from "node:test";
import assert from "node:assert/strict";
import { cachedSeatMap } from "./cached-seat-map.ts";
import type { SeatMapClient } from "./types.ts";
test("cachedSeatMap calls the service once until the entry expires", async () => {
let calls = 0;
const fakeService: SeatMapClient = {
async getSeatMap(showId) {
calls++;
return [`${showId}-A1`];
},
};
let clock = 0;
const seatMap = cachedSeatMap(fakeService, 5000, () => clock);
const signal = new AbortController().signal;
await seatMap.getSeatMap("spring", signal);
await seatMap.getSeatMap("spring", signal);
assert.equal(calls, 1);
clock = 5000; // the entry is now too old
await seatMap.getSeatMap("spring", signal);
assert.equal(calls, 2);
});
Output of npx tsx --test cached-seat-map.test.ts:
✔ cachedSeatMap calls the service once until the entry expires (0.430875ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
fakeService.getSeatMap takes only showId. That’s allowed, because TypeScript accepts a function with fewer parameters where more are offered. new AbortController().signal is a signal that never fires. The “before” cache read Date.now() inside the handler, so a test had to wait five real seconds or mock the clock.
Connect only when the first page needs it
Creating SeatMapHttpClient opens a connection, which the fake shows with its [seats] connecting line. The nightly show import and the tests start the app but never show a seat map, yet every start still connects.
A virtual proxy creates an expensive object only when it’s first needed. It’s another kind of proxy in the GoF book. Save lazy-seat-map.ts:
import type { SeatMapClient } from "./types.ts";
// Proxy: creates the real client on the first call, not at start-up
export function lazySeatMap(create: () => SeatMapClient): SeatMapClient {
let client: SeatMapClient | undefined;
return {
getSeatMap(showId, signal) {
client ??= create();
return client.getSeatMap(showId, signal);
},
};
}
client ??= create() assigns only when client is null or undefined, so create runs once. In proxy-next.ts, only the wiring changes, and the line marked NEW puts one proxy inside the other:
import { cachedSeatMap } from "./cached-seat-map.ts";
import { lazySeatMap } from "./lazy-seat-map.ts";
import { SeatMapHttpClient } from "./seat-map-fake.ts";
import type { SeatMapClient } from "./types.ts";
const seatMap = cachedSeatMap(
lazySeatMap(() => new SeatMapHttpClient("https://seats.tinytickets.example")), // NEW
5000,
);
console.log("TinyTickets started");
// GET /shows/:id/seats: unchanged
async function seatsPage(seatMap: SeatMapClient, showId: string): Promise<string> {
const seats = await seatMap.getSeatMap(showId, AbortSignal.timeout(2000));
return `${showId}: ${seats.length} free seats`;
}
for (const showId of ["spring", "spring"]) {
console.log(await seatsPage(seatMap, showId));
}
Output:
TinyTickets started
[seats] connecting to https://seats.tinytickets.example
[seats] GET https://seats.tinytickets.example/shows/spring/seats
spring: 2 free seats
spring: 2 free seats
The connection now happens at the first page view, after start-up. seatsPage didn’t change.
The built-in Proxy object
A hand-written wrapper must write out every method of the interface it wraps, as logCharges did. With one method that’s easy, but with ten it’s tedious. JavaScript has a built-in class for this, Proxy, with the same name as the pattern.
new Proxy(target, handler) returns an object that runs your handler functions when code reads a property, calls a function or sets a value. These handler functions are called traps. The built-in Proxy can implement the Proxy pattern or a decorator for any object, but it isn’t the pattern itself.
Here it logs every method call on the order store. Save js-proxy.ts:
import { memoryOrders } from "./memory-orders.ts";
// The built-in Proxy object: log every method call on any object
function logCalls<T extends object>(target: T, label: string): T {
return new Proxy(target, {
get(obj, property, receiver) {
const value: unknown = Reflect.get(obj, property, receiver);
if (typeof value !== "function") return value;
return (...args: unknown[]) => {
console.log(`[log] ${label}.${String(property)} called`);
const result: unknown = value.apply(obj, args); // "this" is the real object
return result;
};
},
});
}
const orders = logCalls(memoryOrders(), "orders");
await orders.save({
id: "order-1", showId: "spring", buyerEmail: "ana@example.com",
quantity: 2, totalCents: 2550, status: "paid",
});
const found = await orders.findById("order-1");
console.log(found?.status);
Output:
[log] orders.save called
[db] saved order-1 (paid)
[log] orders.findById called
paid
The get trap runs on every property read. Reflect.get does the normal read, and the code checks the result with typeof. When the value is a method, the trap returns a new function that logs and then calls the real method.
The built-in Proxy has four costs:
- Types.
logCallsreturnsT, so TypeScript believes the object is unchanged. If a trap changed what a method returns, the types would be wrong, andtsccouldn’t warn you. - Private fields. A method that uses a
#field fails whenthisis the proxy. MDN explains this under no private field forwarding.logCallsavoids it by callingvalue.apply(obj, args)with the real object. - Speed. Every property read runs your trap, even reads the trap ignores. This course hasn’t measured the cost, so measure it before you put a proxy on code that runs very often.
- Debugging. Stack traces show the trap and the inner arrow function. The proxy is also a different object from its target, so
===between them givesfalse.
Use the built-in Proxy when you must wrap objects whose methods you don’t know in advance, as a library does. For one interface you know, a hand-written proxy is shorter to read and fully typed.
When a Proxy is worth its cost
Use a Proxy when:
- callers repeat slow or costly calls with the same arguments, and slightly old answers are fine
- creating the real object is expensive and often not needed
- access must be checked in one place before the real object runs
Skip it when:
- the data must be exact, such as whether a seat is still free at the moment of payment. Call the real service there.
- one caller needs a cache. A
Mapin that caller is fine until a second caller appears. - the real service already caches, or an HTTP cache in front of it does
A cache holds memory for every key it has seen. This one never removes old entries, so a real one needs a size limit. Readers also see old data for up to ttlMs.
A lazy proxy moves a start-up error, such as a wrong URL, to the first request, where it’s harder to notice. Each proxy also adds a layer to read and a line to stack traces.
Exercise: a protection proxy
A protection proxy checks access before it calls the real object. Write onSaleOnly(client: SeatMapClient, onSale: ReadonlySet<string>): SeatMapClient. It throws "<showId> is not on sale" for shows that aren’t in the set, and calls the real client for the others. ReadonlySet is a Set type with no methods that change it.
Answer
on-sale-only.ts:
import { SeatMapHttpClient } from "./seat-map-fake.ts";
import type { SeatMapClient } from "./types.ts";
function onSaleOnly(client: SeatMapClient, onSale: ReadonlySet<string>): SeatMapClient {
return {
async getSeatMap(showId, signal) {
if (!onSale.has(showId)) throw new Error(`${showId} is not on sale`);
return client.getSeatMap(showId, signal);
},
};
}
const seatMap = onSaleOnly(new SeatMapHttpClient("https://seats.tinytickets.example"), new Set(["spring"]));
console.log(await seatMap.getSeatMap("spring", AbortSignal.timeout(2000)));
try {
await seatMap.getSeatMap("summer", AbortSignal.timeout(2000));
} catch (err: unknown) {
if (err instanceof Error) console.log(err.message);
}
Output:
[seats] connecting to https://seats.tinytickets.example
[seats] GET https://seats.tinytickets.example/shows/spring/seats
[ 'spring-A1', 'spring-A2' ]
summer is not on sale
The request for summer never reaches the service. Because the shape is the same, you could stack it with the cache: cachedSeatMap(onSaleOnly(client, onSale), 5000).
Composite (short entry): a group that acts like one
When a show sells out, the alert must go to a staff group of two people and to a log. The caller should send one alert, without checking whether it holds one address or a group.
A Composite lets you treat a group of objects the same way as a single object. A group can hold single items and other groups, so callers never check which one they have. Figure 11 shows the “sold out” alert.
[soldOut] (group)
|--> [staff] (group)
| |--> [emailTo("leo@tinytickets.example")]
| |--> [emailTo("maya@tinytickets.example")]
|--> [logAlert]
Every box is an Alert, so a group can sit inside a group.
Figure 11: a group of alerts is itself an alert.
Save composite.ts:
import { MailClient } from "./fakes.ts";
type Alert = (text: string) => Promise<void>;
// Composite: a group of alerts is itself an Alert
function alertGroup(...members: Alert[]): Alert {
return async (text) => {
for (const alert of members) await alert(text);
};
}
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const emailTo = (address: string): Alert => (text) => mail.send(address, text);
const logAlert: Alert = async (text) => console.log(`[log] ${text}`);
const staff = alertGroup(emailTo("leo@tinytickets.example"), emailTo("maya@tinytickets.example"));
const soldOut = alertGroup(staff, logAlert); // a group inside a group
await soldOut("Songs of Spring is sold out");
Output:
[mail] to leo@tinytickets.example: Songs of Spring is sold out
[mail] to maya@tinytickets.example: Songs of Spring is sold out
[log] Songs of Spring is sold out
You need a Composite when your items form a tree, with groups that contain groups. A flat list needs only a for loop. And if one member throws, the loop stops, so the members after it get nothing.
The five wrappers and the built-in Proxy side by side
| Pattern | The problem it solves | What it lets you change | Its cost |
|---|---|---|---|
| Adapter | An SDK’s shape does not fit your interface | Which SDK does the work | One file per SDK; hides what does not fit |
| Facade | Callers repeat the same steps across several services | The steps and their order, in one place | Can grow into a god object |
| Decorator | The same retry or logging code is copied around calls | How a call runs, per caller | Layer order matters; longer stack traces |
| Proxy | A slow or costly object is called too often or too early | When and whether the real call happens | Old data, memory, hidden start-up errors |
Proxy object |
You must wrap methods you do not know in advance | Any property read or call, generically | Weaker types, private fields break, slower reads |
| Composite | Callers must treat one item and a group the same way | How many items, and how they nest | Errors from one member stop the rest |
Figure 12 draws the four full patterns with the same layout. The right column shows the one difference: what the caller sees, compared with what is wrapped.
Caller sees Wrapper Wrapped Difference
[PaymentProvider] (I) --> [walletProvider] --> [WalletSdk] SHAPE CHANGES
[PlaceOrder] --> [placeOrder] --> 3 parts NEW, SIMPLER
[Send] (I) --> [withRetry] --> [Send] (I) SAME + BEHAVIOR
[SeatMapClient] (I) --> [cachedSeatMap] --> [SeatMapClient] SAME + CONTROL
OF THE CALL
Figure 12: all four wrap; only Adapter and Facade change what the caller sees.
So a Decorator and a Proxy can have the same code. A decorator always calls through and adds behavior, while a proxy decides whether, when or how to call through.
Figure 13 starts from the problem in your code. It extends Module 1’s decision figure for wrapping problems.
Something you depend on is awkward to use
|
v
Does the change touch one place you own? -- yes --> No pattern needed.
| no Edit that place.
v
Its shape does not fit your interface? -------- yes --> Adapter
| no
v
Callers repeat steps across several parts? ---- yes --> Facade
| no
v
Same shape, but you need extra work around
every call (retry, log, time)? ---------------- yes --> Decorator
| no
v
Same shape, but you must control whether or
when the real call happens (cache, lazy)? ----- yes --> Proxy
| no
v
One item or a nested group, treated the same? - yes --> Composite
| no
v
No pattern needed. A function is enough.
Figure 13: ask what is wrong with the thing you wrap, and each answer has one pattern.
Check yourself
- What does an Adapter change, and when do you not need one in TypeScript?
- Why should a Facade not collect every operation in the app?
- In
withRetry(withLogging(smsSend), 3), a send fails once and then works. How many[log]lines appear? - A Decorator and a Proxy can have the same code shape. What is the one-line difference?
- Name two costs of JavaScript’s built-in
Proxyobject.
Answers
- It changes the shape of something you can’t edit, such as an SDK, so it fits your interface. You don’t need one when the shapes already match, because structural typing makes the object fit with no code.
- A facade is a simple entry point for one job. When it collects unrelated jobs, it becomes a god object that knows everything, and every change touches it.
- Two.
withLoggingis insidewithRetry, so each attempt runs it (Figure 8). - A decorator always calls through and adds behavior; a proxy decides whether, when or how the real call happens.
- Any two of these:
– TypeScript can’t check what the traps do.
– Methods that use
#private fields fail whenthisis the proxy. – Every property read runs a trap. – Stack traces are longer, and the proxy is a different object from its target.
Lab: retries and push without copied loops
Time: about 20 minutes. Put the files next to fakes.ts.
TinyTickets tells buyers when their tickets are ready. The code uses a new fake push SDK. Save it as push-gateway.ts:
// Fake push SDK with its own shape. It prints instead of calling a real service.
export class PushGateway {
constructor(appKey: string) {
if (appKey === "") throw new Error("PushGateway needs an app key");
}
async publish(note: { device: string; message: string }): Promise<{ accepted: boolean; error?: string }> {
if (!note.device.startsWith("device-")) return { accepted: false, error: "unknown device" };
console.log(`[push] to ${note.device}: ${note.message}`);
return { accepted: true };
}
}
Here is ticket-ready.ts:
import { MailClient } from "./fakes.ts";
import { PushGateway } from "./push-gateway.ts";
export type BuyerContacts = { email: string; deviceToken?: string };
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const gateway = new PushGateway(process.env.PUSH_KEY ?? "test-key");
export async function sendTicketReady(buyer: BuyerContacts, showTitle: string): Promise<void> {
const text = `Your tickets for ${showTitle} are ready`;
for (let attempt = 1; ; attempt++) {
try {
await mail.send(buyer.email, text);
break;
} catch (err: unknown) {
if (attempt === 3) throw err;
}
}
if (buyer.deviceToken !== undefined) {
for (let attempt = 1; ; attempt++) {
const reply = await gateway.publish({ device: buyer.deviceToken, message: text });
if (reply.accepted) break;
if (attempt === 3) throw new Error(`push failed: ${reply.error}`);
}
}
}
The change request is that buyers who give a phone number also get an SMS, with the same three tries. Use SmsClient from fakes.ts. Refactor ticket-ready.ts so that this test file, ticket-ready.test.ts, passes:
import { test } from "node:test";
import assert from "node:assert/strict";
import { gatewaySend, sendTicketReady, withRetry, type Send, type Senders } from "./ticket-ready.ts";
test("each buyer gets the message on every channel they have", async () => {
const sent: string[] = [];
const senders: Senders = {
email: async (to, text) => { sent.push(`email ${to} | ${text}`); },
sms: async (to, text) => { sent.push(`sms ${to} | ${text}`); },
push: async (to, text) => { sent.push(`push ${to} | ${text}`); },
};
await sendTicketReady(senders, { email: "ana@example.com", phone: "+15550100" }, "Songs of Spring");
await sendTicketReady(senders, { email: "chi@example.com", deviceToken: "device-42" }, "Songs of Spring");
assert.deepEqual(sent, [
"email ana@example.com | Your tickets for Songs of Spring are ready",
"sms +15550100 | Your tickets for Songs of Spring are ready",
"email chi@example.com | Your tickets for Songs of Spring are ready",
"push device-42 | Your tickets for Songs of Spring are ready",
]);
});
test("gatewaySend throws when the gateway does not accept the message", async () => {
const fakeGateway = {
async publish() {
return { accepted: false, error: "unknown device" };
},
};
await assert.rejects(gatewaySend(fakeGateway)("device-99", "hi"), /unknown device/);
});
test("withRetry tries three times before it gives up", async () => {
let calls = 0;
const failing: Send = async () => {
calls++;
throw new Error("mail server busy");
};
await assert.rejects(withRetry(failing, 3)("ana@example.com", "hi"), /busy/);
assert.equal(calls, 3);
});
Run it with npx tsx --test ticket-ready.test.ts, and check types with npx tsc --noEmit. Then write run-ticket-ready.ts, which creates the real clients, wraps them and sends to Ana (email and SMS) and Chi (email and push).
Pause and predict: which part of the old code is an adapter waiting to be written, and which part is a decorator?
Hint 1
The push loop does two jobs. It translates { accepted: false } into a failure, which is an adapter’s job, and it retries, which is a decorator’s job. Separate them, and the email loop and the push loop become the same retry.
Hint 2
gatewaySend(gateway) returns a Send that throws when reply.accepted is false, as textBlastSend did in the Adapter exercise. withRetry can be the one from this module, without the log line.
Hint 3
sendTicketReady takes senders: Senders, where Senders is Record<Channel, Send> and Channel is "email" | "sms" | "push", as in the Module 1 lab. It creates no clients and has no loops. The retries are added where the clients are created.
Solution
ticket-ready.ts:
import type { PushGateway } from "./push-gateway.ts";
export type Send = (to: string, text: string) => Promise<void>;
export type Channel = "email" | "sms" | "push";
export type Senders = Record<Channel, Send>;
export type BuyerContacts = { email: string; phone?: string; deviceToken?: string };
// Adapter: makes the push SDK fit Send
export function gatewaySend(gateway: PushGateway): Send {
return async (to, text) => {
const reply = await gateway.publish({ device: to, message: text });
if (!reply.accepted) throw new Error(`push failed: ${reply.error}`);
};
}
// Decorator: same Send shape, plus retries
export function withRetry(send: Send, attempts: number): Send {
return async (to, text) => {
for (let attempt = 1; ; attempt++) {
try {
await send(to, text);
return;
} catch (err: unknown) {
if (attempt >= attempts) throw err;
}
}
};
}
export async function sendTicketReady(senders: Senders, buyer: BuyerContacts, showTitle: string): Promise<void> {
const text = `Your tickets for ${showTitle} are ready`;
await senders.email(buyer.email, text);
if (buyer.phone !== undefined) await senders.sms(buyer.phone, text);
if (buyer.deviceToken !== undefined) await senders.push(buyer.deviceToken, text);
}
run-ticket-ready.ts:
import { MailClient, SmsClient } from "./fakes.ts";
import { PushGateway } from "./push-gateway.ts";
import { gatewaySend, sendTicketReady, withRetry, type Senders } from "./ticket-ready.ts";
// Each client is created once, here, and wrapped once
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
const gateway = new PushGateway(process.env.PUSH_KEY ?? "test-key");
const senders: Senders = {
email: withRetry((to, text) => mail.send(to, text), 3),
sms: withRetry((to, text) => sms.send(to, text), 3),
push: withRetry(gatewaySend(gateway), 3),
};
await sendTicketReady(senders, { email: "ana@example.com", phone: "+15550100" }, "Songs of Spring");
await sendTicketReady(senders, { email: "chi@example.com", deviceToken: "device-42" }, "Songs of Spring");
Output of npx tsx run-ticket-ready.ts:
[mail] to ana@example.com: Your tickets for Songs of Spring are ready
[sms] to +15550100: Your tickets for Songs of Spring are ready
[mail] to chi@example.com: Your tickets for Songs of Spring are ready
[push] to device-42: Your tickets for Songs of Spring are ready
The test passes with ℹ tests 3, ℹ pass 3 and ℹ fail 0. The push adapter throws where the old loop checked accepted, so withRetry treats a refused push and a failed email the same way. SMS needed one line in senders and one if in sendTicketReady. The fakeGateway in the test fits PushGateway, because the class has no private fields.
This solution leaves three things as they were. A failed email still stops the push, as before, because sending the channels independently is a different change. Retries still run with no wait between tries, as the old loops did, and Module 9 adds waits. And it adds no Facade, because sendTicketReady is already one short function with one caller.
Which pattern, if any?
Scenario 1: a new header for the seat-map service
All calls to the seat-map service go through this file, seat-map-http.ts. Three routes import seatMap.
import type { SeatMapClient } from "./types.ts";
// Fake HTTP call. It prints instead of calling the seat-map service.
async function request(url: string, headers: Record<string, string>): Promise<string[]> {
console.log(`[seats] GET ${url} ${JSON.stringify(headers)}`);
return ["spring-A1", "spring-A2"];
}
// The one place in TinyTickets that calls the seat-map service
export const seatMap: SeatMapClient = {
async getSeatMap(showId, signal) {
signal.throwIfAborted();
const url = `https://seats.tinytickets.example/shows/${showId}/seats`;
return request(url, { accept: "application/json" });
},
};
console.log(await seatMap.getSeatMap("spring", AbortSignal.timeout(2000)));
signal.throwIfAborted() throws if the signal has already fired. The new requirement is that, from next month, every request to the seat-map service must send the header x-api-version: 2. A teammate suggests a Decorator, withApiVersion, or a built-in Proxy that adds the header to every call. What do you do?
Hint
Count the places that build the request headers. Start at the first question of Figure 13.
Strong answer
No pattern is needed. The headers are built in one place that TinyTickets owns, so the change is one edit:
// excerpt: the new last line of getSeatMap in seat-map-http.ts
return request(url, { accept: "application/json", "x-api-version": "2" });
The output becomes [seats] GET https://seats.tinytickets.example/shows/spring/seats {"accept":"application/json","x-api-version":"2"}, then the seat list. A decorator would add a file and a layer to protect a change that touches one line. It would be worth its cost if several clients needed the header, or if seatMap were an SDK you couldn’t edit.
Scenario 2: an audit line for every charge
TinyTickets charges through the three providers from the Adapter section: cardProvider, walletProvider and bankTransferProvider. Both chargeOrder and placeOrder call them.
Leo’s accountant has a new requirement. Every charge, for every provider, must write one audit line with the provider name, the amount and the result. Later, the audit log will go to a file instead of the console.
Hint
The shape PaymentProvider does not change. The behavior is the same for every provider. How many callers would you edit if you added the line inside them?
Strong answer
Use a Decorator around PaymentProvider, applied where the providers are created. Every caller gets it, and no caller or adapter changes. Save audit.ts next to the earlier files:
import { BankApi } from "./bank-sdk.ts";
import { bankTransferProvider } from "./bank-provider.ts";
import { PayClient } from "./fakes.ts";
import { cardProvider, walletProvider } from "./providers.ts";
import type { PaymentProvider } from "./types.ts";
import { WalletSdk } from "./wallet-sdk.ts";
type Method = "card" | "wallet" | "bank";
type AuditLog = (line: string) => Promise<void>;
// Decorator: same PaymentProvider shape, plus an audit line per charge
function withAudit(method: Method, provider: PaymentProvider, audit: AuditLog): PaymentProvider {
return {
async charge(amountCents) {
const result = await provider.charge(amountCents);
await audit(`${method} ${amountCents} ${result.status}`);
return result;
},
};
}
const audit: AuditLog = async (line) => console.log(`[audit] ${line}`);
const providers: Record<Method, PaymentProvider> = {
card: withAudit("card", cardProvider(new PayClient("test-key")), audit),
wallet: withAudit("wallet", walletProvider(new WalletSdk("merchant-7")), audit),
bank: withAudit("bank", bankTransferProvider(new BankApi()), audit),
};
await providers.card.charge(2550);
await providers.wallet.charge(15000);
Output:
[pay] charged 2550 cents
[audit] card 2550 paid
[wallet] payment of 150.00 USD
[audit] wallet 15000 declined
AuditLog is a function type, so moving the log to a file later changes one line of wiring. It’s not a Proxy, because every charge goes through, and it’s not an Adapter, because the shape stays the same. A line inside chargeOrder would miss placeOrder, and a line inside each adapter would be written three times.
Get feedback on your answer
Copy this prompt into an AI assistant, with your answer pasted at the end:
I am learning design patterns in TypeScript and Node.js. I read about
Adapter, Facade, Decorator, Proxy and Composite. Here is a scenario and
my answer. Tell me: (1) whether a pattern is needed at all, (2) if so,
whether I picked the right one and why, (3) one cost of my answer, and
(4) one simpler option if there is one. Do not rewrite my code unless I
ask. Keep the answer under 200 words.
Scenario: <paste the scenario and its code>
My answer: <paste your answer>
Going deeper
You can skip this section. It covers the class form of these wrappers, one more cache problem, and where Node.js and libraries use these patterns.
The class form
This module wrote every wrapper as a function that returns an object or a function. Here is the wallet Adapter as a class, wallet-provider-class.ts:
import type { PaymentProvider, PaymentResult } from "./types.ts";
import { WalletSdk } from "./wallet-sdk.ts";
// The same Adapter as a class
export class WalletProvider implements PaymentProvider {
#wallet: WalletSdk;
constructor(wallet: WalletSdk) {
this.#wallet = wallet;
}
async charge(amountCents: number): Promise<PaymentResult> {
const response = await this.#wallet.createPayment({
amount: { value: (amountCents / 100).toFixed(2), currency: "USD" },
});
if (response.state === "SUCCEEDED") {
return { status: "paid", chargeId: response.paymentRef };
}
return { status: "declined", reason: response.refusalCode };
}
}
const provider = new WalletProvider(new WalletSdk("merchant-7"));
console.log(await provider.charge(2550));
Output:
[wallet] payment of 25.50 USD
{ status: 'paid', chargeId: 'wp_1' }
Both forms work. The class form is common in NestJS, a Node.js framework that creates each of its service classes for you (Module 6). There, a Facade such as placeOrder is often a class named CheckoutService.
Pick a class when the wrapper keeps state that changes, such as a token it refreshes. A class also fits when the wrapper gains a second operation that shares the same parts, such as refundOrder next to placeOrder.
Many cache misses at once
When ten requests miss cachedSeatMap at the same moment, all ten still call the service. Caching the promise instead of the result fixes that, but it takes more code.
Where Node.js and libraries use these patterns
- Adapter.
util.promisifytakes a function in the old callback style and returns one that returns a promise. - Facade.
http.getis a small facade overhttp.request. It sets the method to GET and callsreq.end()for you. - Decorator.
util.deprecatewraps a function and prints a deprecation warning the first time the wrapped function is called. - Virtual proxy. TypeORM is an ORM, a library that maps database tables to classes. Its lazy relations load related rows only when your code first reads the property.
- Built-in
Proxy. Vue 3 uses it for its reactive objects, so the page can update when data changes, as its guide to how reactivity works explains.
Cheat sheet
| Pattern | The problem it solves | The signal in your code |
|---|---|---|
| Adapter | An SDK’s shape does not fit your interface | SDK types or words (“SUCCEEDED”) in business logic |
| Facade | Callers repeat the same steps across several services | Two routes with the same four lines in the same order |
| Decorator | The same retry or logging code is copied around calls | The same retry loop or log line in several functions |
| Proxy | A slow or costly object is called too often or too early | A cache Map or “connect on first use” inside a handler |
Proxy object |
You must wrap methods you do not know in advance | A wrapper that must forward ten methods by hand |
| Composite | Callers must treat one item and a group the same way | if (Array.isArray(x)) before every call |
| No pattern | The change touches one place you own | One line to edit, and it is easy to test |
- Interface: an Adapter changes the shape; a Facade offers a new, simpler one; a Decorator keeps it and adds behavior; a Proxy keeps it and controls the call.
- Where to wrap: apply wrappers where the clients are created, so neither the callers nor the wrapped code change.
- Order: a wrapper outside
withRetryruns once per call; a wrapper inside it runs once per attempt. - Cost: each wrapper adds a file, a layer and a line in stack traces. If the change touches one place you own, edit that place.
- Built-in
Proxy: it wraps methods you don’t know in advance, but its types can be wrong and#fields break through it.
Next, Module 4 teaches Strategy, State and Command, for code that picks one behavior out of several at run time, such as what a cancelled order may still do.
Sources
- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994. The structural patterns Adapter, Facade, Decorator, Proxy and Composite, and the kinds of proxy.
- TypeScript handbook: type compatibility, private and protected members.
- MDN: Proxy, no private field forwarding, Reflect.
- Node.js documentation:
util.promisify,util.deprecate,http.get, test runner, assert. - TypeORM: eager and lazy relations.
- Vue: reactivity in depth.