Design Patterns in Plain Words / Module 06

Module 6: Wiring an App

Dependency Injection, the composition root, and when a container such as NestJS is worth adding.

Leo wanted to rehearse the spring sale on the staging server with his team. “Nobody gets a real email, and no card gets charged,” he said. Maya searched the code for new MailClient. She found it in three files, each with its own settings, and two of them disagreed about the mail host.

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

Every function in TinyTickets does its job, but the clients those functions use are created in many places. This module moves all of that creation into one file, first by hand and then with NestJS, a framework for Node.js backends. You’ll also see when each step is worth its cost.

After this module, you can:

  • change a function so that it receives its clients, settings and clock instead of creating them, and test it with plain fakes
  • move every new SomeClient(...) and every process.env read into one file, and switch the whole app to a staging setup with one change
  • wire the same checkout with NestJS, and say what that adds and what it costs
  • decide when hand-written wiring is enough and when a library for it is worth adding

Set up the folder for this module

Use the folder from Module 1, with its fakes.ts and tsconfig.json. As in every module, the provider clients are fakes that print a line instead of calling a real service. This module adds three small files that the examples share.

types.ts is the shared types file from Module 3. In this module it holds:

// Shared TinyTickets types for this module
export type ShowId = string;
export interface Show { id: string; title: string; date: string; priceCents: number }
export type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";
export interface Order {
  id: string;
  showId: string;
  buyerEmail: string;
  quantity: number;
  totalCents: number;
  status: OrderStatus;
}
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>;

providers.ts holds two fake payment providers. Each one fits PaymentProvider by shape, with no implements:

// Fake payment providers. They print instead of calling a real service.
import type { PaymentResult } from "./types.ts";

export class CardProvider {
  constructor(apiKey: string) {
    if (apiKey === "") throw new Error("CardProvider needs an API key");
  }
  async charge(amountCents: number): Promise<PaymentResult> {
    console.log(`[card] charged ${amountCents} cents`);
    return { status: "paid", chargeId: "card_1" };
  }
}

export class WalletProvider {
  constructor(apiKey: string) {
    if (apiKey === "") throw new Error("WalletProvider needs an API key");
  }
  async charge(amountCents: number): Promise<PaymentResult> {
    console.log(`[wallet] charged ${amountCents} cents`);
    return { status: "paid", chargeId: "wallet_1" };
  }
}

shows.ts holds the shows on sale:

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

// The shows on sale. In the real app they come from the database.
export const shows = new Map<string, Show>([
  ["spring", { id: "spring", title: "Songs of Spring", date: "2027-03-14", priceCents: 1200 }],
  ["summer", { id: "summer", title: "Summer Lights", date: "2027-06-20", priceCents: 1500 }],
]);

Dependency Injection: hand a function what it needs

A checkout that nobody can test

Leo wanted proof before the spring sale opened. A group of four should pay $48, with no booking fee. Maya wanted a test for it, and the test must charge no card and send no email. Here is the checkout code she had, checkout-before.ts:

import { MailClient } from "./fakes.ts";
import { CardProvider } from "./providers.ts";
import { shows } from "./shows.ts";
import type { Order } from "./types.ts";

let nextOrder = 1;

export async function checkout(showId: string, quantity: number, buyerEmail: string): Promise<Order> {
  const show = shows.get(showId);
  if (show === undefined) throw new Error(`no such show: ${showId}`);
  const fee = quantity >= 4 ? 0 : 150;
  const totalCents = show.priceCents * quantity + fee;

  const payments = new CardProvider(process.env.CARD_KEY ?? "test-key");
  const result = await payments.charge(totalCents);
  if (result.status === "declined") throw new Error(`payment declined: ${result.reason}`);

  const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
  await mail.send(buyerEmail, `Your tickets for ${show.title}`);
  return { id: `order-${nextOrder++}`, showId, buyerEmail, quantity, totalCents, status: "paid" };
}

const order = await checkout("spring", 2, "ana@example.com");
console.log(order.id, order.totalCents, order.status);

Pause and predict: what total does the last line print for two tickets to the spring show? Write the number down, then run the file.

Output of npx tsx checkout-before.ts:

[card] charged 2550 cents
[mail] to ana@example.com: Your tickets for Songs of Spring
order-1 2550 paid

The total is 2 × 1200 + 150 = 2550 cents, because a group under four pays the 150-cent booking fee. The trouble is the two new lines.

A test that calls checkout runs the real CardProvider and the real MailClient, because nothing lets the test hand in different ones. The test can’t even see the amount that was charged.

Figure 1 shows the problem. It also repeats the legend used in every figure of this course.

(Buyer) --> [checkout]
[checkout] ==> [CardProvider]    new CardProvider(CARD_KEY)
[checkout] ==> [MailClient]      new MailClient(SMTP_HOST)
[checkout.test.ts] --> [checkout]
    the test cannot reach either ==> arrow

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: checkout creates both of its clients, so no caller can replace them.

Pause and predict: checkout needs two things from outside, a way to charge and a way to send email. Who should create them, and how should they reach checkout? Write your answer before you read on.

The idea: receive what you need, don’t create it

A dependency is anything your code needs from outside itself to do its job, such as a client, a setting, the clock or a source of random ids. Dependency Injection (DI) means a function or class receives its dependencies from its caller, instead of creating them itself. “Injection” only means “handing in”. The caller can hand them in through a parameter, a constructor or a deps object, which is one object that holds all the dependencies.

So DI lets you change which object fills each dependency (card or wallet, real or fake) without touching the code that uses it.

Think of a cordless drill. The drill doesn’t make its own battery. It has a slot of a fixed shape, and any battery that fits can go in. Figure 2 puts the drill next to the checkout code, with matching parts on the same row.

The cordless drill                    The checkout code
[drill] --> [slot] (I)                [checkout] --> [PaymentProvider] (I)
[battery] ..> [slot] (I)              [CardProvider] ..> [PaymentProvider] (I)

Figure 2: the drill uses whatever battery fits its slot; checkout uses whatever provider fits PaymentProvider.

In code, checkout receives any object that fits PaymentProvider, real or fake. The file that runs checkout chooses which one.

The fix: a deps object, and one place that fills it

checkout stops creating clients. Instead, a factory function (a function that builds and returns something, as in Module 2) takes the dependencies once and returns the checkout function. Save checkout.ts:

import { shows } from "./shows.ts";
import type { Order, PaymentProvider, Send } from "./types.ts";

export interface CheckoutDeps {
  payments: PaymentProvider;
  sendEmail: Send;
}
export type Checkout = (showId: string, quantity: number, buyerEmail: string) => Promise<Order>;

export function makeCheckout(deps: CheckoutDeps): Checkout {
  let nextOrder = 1;
  return async (showId, quantity, buyerEmail) => {
    const show = shows.get(showId);
    if (show === undefined) throw new Error(`no such show: ${showId}`);
    const fee = quantity >= 4 ? 0 : 150;
    const totalCents = show.priceCents * quantity + fee;

    const result = await deps.payments.charge(totalCents);
    if (result.status === "declined") throw new Error(`payment declined: ${result.reason}`);

    await deps.sendEmail(buyerEmail, `Your tickets for ${show.title}`);
    return { id: `order-${nextOrder++}`, showId, buyerEmail, quantity, totalCents, status: "paid" };
  };
}

The returned function is a closure, a function that keeps the variables around it (Module 1). Here it keeps deps and its own nextOrder counter. checkout.ts imports no client and reads no process.env, so it depends only on two shapes from types.ts.

The real clients are now created by the file that runs the code. Save checkout-main.ts:

import { MailClient } from "./fakes.ts";
import { CardProvider } from "./providers.ts";
import { makeCheckout } from "./checkout.ts";

// The real objects are created here, once, and handed to makeCheckout
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const checkout = makeCheckout({
  payments: new CardProvider(process.env.CARD_KEY ?? "test-key"),
  sendEmail: (to, text) => mail.send(to, text),
});

const order = await checkout("spring", 2, "ana@example.com");
console.log(order.id, order.totalCents, order.status);

npx tsx checkout-main.ts prints the same three lines as the “before” version. sendEmail is a small arrow function around mail.send, so checkout depends on the Send function type, not on MailClient. Figure 3 shows how the arrows moved.

Before
  [checkout] ==> [CardProvider]
  [checkout] ==> [MailClient]

After
  [checkout-main.ts] ==> [CardProvider] ..> [PaymentProvider] (I)
  [checkout-main.ts] ==> [MailClient]
  [checkout-main.ts] --> [makeCheckout]                          NEW
  [makeCheckout] ==> [checkout] --> [PaymentProvider] (I), [Send]
  [checkout.test.ts] ==> [fakes] ..> [PaymentProvider] (I), [Send]  NEW

Figure 3: the ==> arrows moved out of checkout and into the file that runs it.

Prove it with a test

Now the test Maya wanted. The fakes are plain objects and functions that record what happened, as in Module 1. Save checkout.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import { makeCheckout } from "./checkout.ts";
import type { PaymentProvider, PaymentResult, Send } from "./types.ts";

function fakes(result: PaymentResult) {
  const log: string[] = [];
  const payments: PaymentProvider = {
    async charge(amountCents) {
      log.push(`charge ${amountCents}`);
      return result;
    },
  };
  const sendEmail: Send = async (to, text) => {
    log.push(`email ${to} | ${text}`);
  };
  return { log, payments, sendEmail };
}

test("a group of four pays no booking fee", async () => {
  const { log, payments, sendEmail } = fakes({ status: "paid", chargeId: "ch_test" });
  const checkout = makeCheckout({ payments, sendEmail });

  const order = await checkout("spring", 4, "ben@example.com");

  assert.equal(order.totalCents, 4800);
  assert.deepEqual(log, ["charge 4800", "email ben@example.com | Your tickets for Songs of Spring"]);
});

test("a declined payment sends no email", async () => {
  const { log, payments, sendEmail } = fakes({ status: "declined", reason: "card expired" });
  const checkout = makeCheckout({ payments, sendEmail });

  await assert.rejects(checkout("spring", 2, "ana@example.com"), /card expired/);
  assert.deepEqual(log, ["charge 2550"]);
});

Output of npx tsx --test checkout.test.ts:

✔ a group of four pays no booking fee (0.884875ms)
✔ a declined payment sends no email (0.253125ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

The times and a few summary lines differ on your machine. The second test checks a path the “before” code couldn’t reach without a real declined card. The order stops after the charge, and no email goes out. assert.rejects waits for the promise and passes only if it rejects with a matching error.

Rule: A function that receives its dependencies can be tested with plain fakes; a function that creates them can’t.

The next change: a wallet provider

Leo signed up with a wallet provider and wants to stop taking cards for now. With DI, the change is two lines in checkout-main.ts. This is an excerpt, and the rest of the file stays the same:

import { WalletProvider } from "./providers.ts";
  payments: new WalletProvider(process.env.WALLET_KEY ?? "test-key"),

Output:

[wallet] charged 2550 cents
[mail] to ana@example.com: Your tickets for Songs of Spring
order-1 2550 paid

checkout.ts and checkout.test.ts didn’t change, and the tests still pass. Choosing between card and wallet for each order is a different change, and Module 4 solved it with the Strategy pattern.

The class form: constructor injection

The fix used the function form. The class form passes the dependencies to the constructor instead, which is called constructor injection. NestJS expects this form, so you’ll meet it again later in this module. Save checkout-service.ts:

import { MailClient } from "./fakes.ts";
import { CardProvider } from "./providers.ts";
import { shows } from "./shows.ts";
import type { Order, PaymentProvider, Send } from "./types.ts";

// Class form: the dependencies arrive through the constructor
export class CheckoutService {
  readonly #payments: PaymentProvider;
  readonly #sendEmail: Send;
  #nextOrder = 1;

  constructor(payments: PaymentProvider, sendEmail: Send) {
    this.#payments = payments;
    this.#sendEmail = sendEmail;
  }

  async checkout(showId: string, quantity: number, buyerEmail: string): Promise<Order> {
    const show = shows.get(showId);
    if (show === undefined) throw new Error(`no such show: ${showId}`);
    const totalCents = show.priceCents * quantity + (quantity >= 4 ? 0 : 150);
    const result = await this.#payments.charge(totalCents);
    if (result.status === "declined") throw new Error(`payment declined: ${result.reason}`);
    await this.#sendEmail(buyerEmail, `Your tickets for ${show.title}`);
    const id = `order-${this.#nextOrder++}`;
    return { id, showId, buyerEmail, quantity, totalCents, status: "paid" };
  }
}

const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const service = new CheckoutService(
  new CardProvider(process.env.CARD_KEY ?? "test-key"),
  (to, text) => mail.send(to, text),
);
const order = await service.checkout("spring", 2, "ana@example.com");
console.log(order.id, order.totalCents, order.status);

It prints the same three lines. A field whose name starts with # is a private field, which code outside the class can’t read, as the MDN page on private fields explains.

Constructor injection and the deps object hand in everything when the object is created. Parameter injection hands a dependency in on every call instead, as remindBuyer(sender, ...) did in Module 1.

Use the function form for one function, or for a few functions that share nothing, because it’s shorter. Use the class form when several methods share the same dependencies, or when the framework expects classes, as NestJS does.

When to use DI, and when to skip it

Use it when you see these signals in the code:

  • new SomeClient(...) inside business logic, as in Figure 1
  • process.env.SOMETHING read inside a function that is not the entry point
  • new Date(), Date.now() or Math.random() inside a rule you want to test, because the clock and randomness are dependencies too
  • a test that needs a mocking tool to replace an import
  • two setups of the same code, such as live and staging, or card and wallet

Skip it when the code has no outside effect or setting, such as a price calculation or a formatter. Those already take plain values. Also skip it for a one-off script with one entry point, where creating the client at the top of the file is simpler.

Don’t inject what never varies and costs nothing to run for real, such as shows.ts here. You can inject it later, when a test needs other shows.

What DI costs

  • More parameters and a deps type. Every dependency becomes a field in CheckoutDeps. A long deps list is a warning that the function does too many jobs.
  • Indirection. “Go to definition” on deps.payments.charge lands on the PaymentProvider interface. To find the code that runs, you open the file that created it.
  • Someone must do the wiring. The new lines didn’t disappear, they moved to the caller. With many entry points, the wiring can spread, and the next section fixes that.
  • Runtime cost. One closure or one object per wired function, created once at startup.

Exercise: find the hidden dependency

This function decides whether a show is still on sale. Save sale-open-before.ts:

import { shows } from "./shows.ts";

// Sales close at 18:00 UTC on the day of the show
export function isSaleOpen(showId: string): boolean {
  const show = shows.get(showId);
  if (show === undefined) return false;
  return new Date() < new Date(`${show.date}T18:00:00Z`);
}

console.log("spring open?", isSaleOpen("spring"));

It prints spring open? true today. Write a test that checks the sale is closed at 18:30 on the day of the show. What must change first?

Answer

The hidden dependency is the clock, because new Date() with no arguments reads the current time. Inject it. The smallest change is a now parameter:

import { shows } from "./shows.ts";

// Sales close at 18:00 UTC on the day of the show
export function isSaleOpen(showId: string, now: Date): boolean {
  const show = shows.get(showId);
  if (show === undefined) return false;
  return now < new Date(`${show.date}T18:00:00Z`);
}

console.log("spring open?", isSaleOpen("spring", new Date()));
console.log("at 18:30 on show day?", isSaleOpen("spring", new Date("2027-03-14T18:30:00Z")));

Output:

spring open? true
at 18:30 on show day? false

The test passes new Date("2027-03-14T18:30:00Z") and expects false. The caller that runs the app passes new Date(). If the function is created once and called many times, inject a function instead, now: () => Date, so each call reads a fresh time.

Composition root: all the wiring in one file

Three files, three ways to create a client

After the DI section, every function in TinyTickets received its clients. So the wiring moved up into the files that start each part of the app. Here are three of those files, shortened and placed in one file so you can run them. Save wiring-before.ts:

import { MailClient, SmsClient } from "./fakes.ts";
import { CardProvider } from "./providers.ts";
import { makeCheckout } from "./checkout.ts";

// routes/checkout.ts: wires its own dependencies
const checkoutMail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const checkout = makeCheckout({
  payments: new CardProvider(process.env.CARD_KEY ?? "test-key"),
  sendEmail: (to, text) => checkoutMail.send(to, text),
});

// routes/resend.ts: a second MailClient, with a different default host
const resendMail = new MailClient(process.env.SMTP_HOST ?? "smtp.tinytickets.example");
async function resendTickets(email: string, title: string): Promise<void> {
  await resendMail.send(email, `Your tickets for ${title} (copy)`);
}

// jobs/reminders.ts: the evening job creates its own SmsClient
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
async function remindBuyer(phone: string, title: string): Promise<void> {
  await sms.send(phone, `Tonight: ${title}. Doors open at 19:00.`);
}

// One sale day, as the three files would run it
const order = await checkout("spring", 2, "ana@example.com");
await resendTickets("ana@example.com", "Songs of Spring");
await remindBuyer("+15550101", "Songs of Spring");
console.log(order.id, order.totalCents, order.status);

Output of npx tsx wiring-before.ts:

[card] charged 2550 cents
[mail] to ana@example.com: Your tickets for Songs of Spring
[mail] to ana@example.com: Your tickets for Songs of Spring (copy)
[sms] to +15550101: Tonight: Songs of Spring. Doors open at 19:00.
order-1 2550 paid

Now Leo’s request from the opening arrives. On staging, nobody is charged and no message reaches a buyer. To add it, Maya must put an if (process.env.APP_ENV === "staging") into each of the three files. If she forgets one, a real buyer gets a real email from a rehearsal.

The files already disagree about one setting. When SMTP_HOST is missing, two of them fall back to different hosts. Figure 4 shows where the wiring lives.

[routes/checkout.ts] ==> [CardProvider]   reads CARD_KEY
[routes/checkout.ts] ==> [MailClient]     reads SMTP_HOST, default A
[routes/resend.ts]   ==> [MailClient]     reads SMTP_HOST, default B
[jobs/reminders.ts]  ==> [SmsClient]      reads SMS_KEY

A staging mode means one more "if" in each of the three files.

Figure 4: each entry file creates its own clients and reads its own settings, so one decision spreads over three files.

Pause and predict: the functions already receive their clients. What would you move, and to where, so that “staging” is decided in one place?

The idea: one place near the entry point

A composition root is the one place, as close as possible to the entry point of the app, where the app creates its objects and connects them. Every other file receives what it needs and creates nothing. So you can change the whole setup of the app (live, staging, test) in one file, without touching any feature code.

Think of the electrical panel in a house. All the power starts at the panel by the door. The rooms use power, and none of them makes its own. Figure 5 puts the panel next to the code.

The house                              The app
[electrical panel] by the door         [main.ts] next to the entry point
  all power starts here                  every client is created here
[kitchen] [bedroom] [hall]             [checkout] [resendTickets]
                                       [remindBuyer]
  use power, never make it               use clients, never create them

Figure 5: the rooms use power from one panel; the features use clients from one root.

In code, main.ts creates every client, and the features only receive them. So a staging setup is one check in one file.

The fix: buildApp connects, main.ts creates

The fix has two files. app.ts connects the features to each other, but it creates no client and reads no setting. Save app.ts:

import { makeCheckout, type Checkout } from "./checkout.ts";
import type { PaymentProvider, Send } from "./types.ts";

// Everything the app needs from the outside world
export interface AppDeps {
  payments: PaymentProvider;
  sendEmail: Send;
  sendSms: Send;
}

export interface App {
  checkout: Checkout;
  resendTickets(email: string, title: string): Promise<void>;
  remindBuyer(phone: string, title: string): Promise<void>;
}

// Connects the parts to each other. It creates no client and reads no setting.
export function buildApp(deps: AppDeps): App {
  return {
    checkout: makeCheckout({ payments: deps.payments, sendEmail: deps.sendEmail }),
    resendTickets: (email, title) => deps.sendEmail(email, `Your tickets for ${title} (copy)`),
    remindBuyer: (phone, title) => deps.sendSms(phone, `Tonight: ${title}. Doors open at 19:00.`),
  };
}

In a real project, resendTickets and remindBuyer live in their own files, like checkout.ts. Here they are one line each to keep the example short.

main.ts is the composition root. It’s the only file that reads process.env and the only file that says new for a client. It also holds Leo’s staging change. Save main.ts:

import { MailClient, SmsClient } from "./fakes.ts";
import { CardProvider } from "./providers.ts";
import { buildApp, type AppDeps } from "./app.ts";
import type { PaymentProvider, Send } from "./types.ts";

// The composition root: the only file that reads settings and creates clients
function liveDeps(): AppDeps {
  const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
  const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
  return {
    payments: new CardProvider(process.env.CARD_KEY ?? "test-key"),
    sendEmail: (to, text) => mail.send(to, text),
    sendSms: (to, text) => sms.send(to, text),
  };
}

// Staging: nobody is charged and no message leaves the server
function stagingDeps(): AppDeps {
  const logOnly: Send = async (to, text) => console.log(`[log] would send to ${to}: ${text}`);
  const noCharge: PaymentProvider = {
    async charge(amountCents) {
      console.log(`[log] would charge ${amountCents} cents`);
      return { status: "paid", chargeId: "staging_1" };
    },
  };
  return { payments: noCharge, sendEmail: logOnly, sendSms: logOnly };
}

const app = buildApp(process.env.APP_ENV === "staging" ? stagingDeps() : liveDeps());

// One sale day
const order = await app.checkout("spring", 2, "ana@example.com");
await app.resendTickets("ana@example.com", "Songs of Spring");
await app.remindBuyer("+15550101", "Songs of Spring");
console.log(order.id, order.totalCents, order.status);

npx tsx main.ts prints the same five lines as wiring-before.ts. The two mail clients became one, with one default host. Now run the staging setup with APP_ENV=staging npx tsx main.ts:

[log] would charge 2550 cents
[log] would send to ana@example.com: Your tickets for Songs of Spring
[log] would send to ana@example.com: Your tickets for Songs of Spring (copy)
[log] would send to +15550101: Tonight: Songs of Spring. Doors open at 19:00.
order-1 2550 paid

Leo’s whole request is one function and one condition, in one file. checkout.ts and app.ts didn’t change. Figure 6 shows the new structure.

[main.ts] reads APP_ENV, CARD_KEY, SMTP_HOST, SMS_KEY      once
[main.ts] ==> [CardProvider] [MailClient] [SmsClient]      live
[main.ts] ==> [noCharge] [logOnly]                         staging  NEW
[main.ts] --> [buildApp]                                   hands in AppDeps
[buildApp] ==> [checkout] [resendTickets] [remindBuyer]
[app.test.ts] --> [buildApp]                               with fakes  NEW

Figure 6: every ==> to a client starts in main.ts; the features only receive.

Rule: Only the composition root reads settings and creates clients; every other file receives them.

Prove it with a test

Because buildApp receives everything from outside, a test can run a whole sale day with plain fakes. Save app.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import { buildApp } from "./app.ts";

test("one sale day runs end to end with fakes", async () => {
  const log: string[] = [];
  const app = buildApp({
    payments: {
      async charge(amountCents) {
        log.push(`charge ${amountCents}`);
        return { status: "paid", chargeId: "ch_test" };
      },
    },
    sendEmail: async (to, text) => {
      log.push(`email ${to} | ${text}`);
    },
    sendSms: async (to, text) => {
      log.push(`sms ${to} | ${text}`);
    },
  });

  await app.checkout("spring", 2, "ana@example.com");
  await app.resendTickets("ana@example.com", "Songs of Spring");
  await app.remindBuyer("+15550101", "Songs of Spring");

  assert.deepEqual(log, [
    "charge 2550",
    "email ana@example.com | Your tickets for Songs of Spring",
    "email ana@example.com | Your tickets for Songs of Spring (copy)",
    "sms +15550101 | Tonight: Songs of Spring. Doors open at 19:00.",
  ]);
});

Output of npx tsx --test app.test.ts:

✔ one sale day runs end to end with fakes (0.827917ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

With the “before” wiring, this test wasn’t possible, because importing routes/checkout.ts created a real CardProvider at once. The test doesn’t cover main.ts itself. That file is thin on purpose, since it only chooses and creates, so one run with APP_ENV=staging is enough to check it.

The next change: log every message in production

The team wants a [log] line before every email and text in production. The wrapper exists already. It’s withLogging from Module 1 (Idea 3), which Module 3 taught as the Decorator pattern, a wrapper with the same shape as the thing it wraps. Save it as with-logging.ts:

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

// The wrapper from Module 1 (Idea 3) and Module 3 (Decorator)
export function withLogging(send: Send): Send {
  return async (to, text) => {
    console.log(`[log] send to ${to}`);
    await send(to, text);
  };
}

Then change three lines in main.ts, inside liveDeps. This is an excerpt:

import { withLogging } from "./with-logging.ts";
    sendEmail: withLogging((to, text) => mail.send(to, text)),
    sendSms: withLogging((to, text) => sms.send(to, text)),

Output of npx tsx main.ts:

[card] charged 2550 cents
[log] send to ana@example.com
[mail] to ana@example.com: Your tickets for Songs of Spring
[log] send to ana@example.com
[mail] to ana@example.com: Your tickets for Songs of Spring (copy)
[log] send to +15550101
[sms] to +15550101: Tonight: Songs of Spring. Doors open at 19:00.
order-1 2550 paid

So the composition root is where wrappers go on, and no feature file knows that logging exists.

When to use a composition root, and when to skip it

Use it when you see these signals:

  • the same client is created in two or more files
  • process.env is read in more than one file, or with different defaults
  • a setup such as “staging” or “test” needs an if in several files
  • a test can’t import a module without creating a real client

Skip it for a single-file script, because the top of that file is already its root. Also skip a separate buildApp while the app has one or two features. A few lines at the top of server.ts are enough until you want a test to run the whole app with fakes.

What a composition root costs

  • One file knows everything. main.ts imports every client and every feature, so it grows with the app. The order of its lines matters too, because you must create a client before you hand it in.
  • Everything is created at startup. A client that is rarely used is still created. You can create it the first time a function needs it instead, but then the root is harder to read.
  • Per-request objects need care. Some objects must be new for each HTTP request, such as a logger that carries the request id. The root can’t create those at startup, so it hands in a factory function that the handler calls.
  • The root itself isn’t unit tested. Keep it thin, so that one run in each setup is enough.

Exercise: one more setting

The venue for the summer show opens its doors at 18:30, not 19:00. Leo wants the door time in the reminder to come from a setting, so he can change it without a code change. Where do you read process.env.DOORS_TIME, and how does the time reach remindBuyer?

Answer

Read it in main.ts and nowhere else, with const doorsTime = process.env.DOORS_TIME ?? "19:00";. Add doorsTime: string to AppDeps, and let buildApp use it in the reminder text. A setting is a dependency like a client, so it arrives the same way.

app.test.ts then passes doorsTime: "18:30" and checks the text. If remindBuyer read process.env itself, the test would have to change the process environment. Every test that runs after it would see that change too.

Containers: let a library write the wiring

A hand-written root is enough for an app the size of TinyTickets. It gets harder when the app has dozens of services and the order of creation matters. A DI container is a library that creates your objects from a list of recipes, works out the order, and hands each object its dependencies. This section wires the same checkout with NestJS, so you can compare it with main.ts.

Install NestJS

The examples use NestJS 12.5. Install it in your patterns folder:

npm install @nestjs/core @nestjs/common reflect-metadata rxjs

@nestjs/core has the container, and @nestjs/common has the decorators. NestJS also needs reflect-metadata and rxjs installed next to it, and it imports them itself.

Give the NestJS files their own tsconfig

Module 1 showed decorators, the @name(...) lines placed above a class or method to change it. NestJS uses an older kind, turned on by the experimentalDecorators setting, not the standard decorators from TypeScript 5.0. The @ looks the same, but the two kinds are different functions, and one project can’t mix them. This @ syntax is also not the Decorator pattern from Module 3.

So the NestJS files go in their own folder, nest/, with their own tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2023",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "skipLibCheck": true,
    "types": ["node"],
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

The experimentalDecorators setting turns on the older decorators, including decorators on constructor parameters. The emitDecoratorMetadata setting tells tsc to record the type of each constructor parameter, which NestJS can read. The NestJS starter project turns on both.

In the main tsconfig.json one folder up, add "exclude": ["nest"], so tsc doesn’t check the NestJS files with the wrong settings. Then run the NestJS files from inside nest/, because tsx reads the tsconfig.json of the folder you run it from. From the parent folder, tsx fails with “Parameter decorators only work when experimental decorators are enabled”.

The service and its tokens

The service is the class form from the DI section, with three decorators added. Save nest/checkout.service.ts:

import { Inject, Injectable } from "@nestjs/common";
import { shows } from "../shows.ts";
import type { Order, PaymentProvider, Send } from "../types.ts";

// Tokens: names the container uses to find a dependency at run time
export const PAYMENTS = "PAYMENTS";
export const SEND_EMAIL = "SEND_EMAIL";

@Injectable()
export class CheckoutService {
  #nextOrder = 1;

  constructor(
    @Inject(PAYMENTS) private readonly payments: PaymentProvider,
    @Inject(SEND_EMAIL) private readonly sendEmail: Send,
  ) {}

  async checkout(showId: string, quantity: number, buyerEmail: string): Promise<Order> {
    const show = shows.get(showId);
    if (show === undefined) throw new Error(`no such show: ${showId}`);
    const totalCents = show.priceCents * quantity + (quantity >= 4 ? 0 : 150);
    const result = await this.payments.charge(totalCents);
    if (result.status === "declined") throw new Error(`payment declined: ${result.reason}`);
    await this.sendEmail(buyerEmail, `Your tickets for ${show.title}`);
    const id = `order-${this.#nextOrder++}`;
    return { id, showId, buyerEmail, quantity, totalCents, status: "paid" };
  }
}

@Injectable() marks the class as one that the container creates. A token is the name the container uses to find a dependency, and here it’s a string. @Inject(PAYMENTS) tells NestJS which token fills that constructor parameter.

private readonly payments: PaymentProvider in the parameter list is a parameter property. It declares a field and assigns the argument to it in one step, as the TypeScript handbook shows.

Note: This course avoids parameter properties elsewhere, because Node.js can’t run them by deleting the types alone. NestJS code uses them everywhere, so this example does too.

The module: a list of recipes

A NestJS module is a class marked with @Module that holds the list of recipes. Save nest/main.ts:

import { Module } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { MailClient } from "../fakes.ts";
import { CardProvider } from "../providers.ts";
import type { Send } from "../types.ts";
import { CheckoutService, PAYMENTS, SEND_EMAIL } from "./checkout.service.ts";

// The recipes. NestJS reads them and decides the order of creation.
@Module({
  providers: [
    CheckoutService,
    {
      provide: PAYMENTS,
      useFactory: () => new CardProvider(process.env.CARD_KEY ?? "test-key"),
    },
    {
      provide: SEND_EMAIL,
      useFactory: (): Send => {
        const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
        return (to, text) => mail.send(to, text);
      },
    },
  ],
})
class AppModule {}

// No HTTP server here: an application context is the container on its own
const app = await NestFactory.createApplicationContext(AppModule, { logger: false });
const order = await app.get(CheckoutService).checkout("spring", 2, "ana@example.com");
console.log(order.id, order.totalCents, order.status);
await app.close();

Output of cd nest && npx tsx main.ts:

[card] charged 2550 cents
[mail] to ana@example.com: Your tickets for Songs of Spring
order-1 2550 paid

The same three lines again. A provider is one recipe in the providers list. A class name alone means “create it with new“. An object with provide and useFactory means “call this function to get the value for this token”.

createApplicationContext builds the container without an HTTP server. Then app.get(CheckoutService) asks it for the finished object, and { logger: false } turns off NestJS’s startup log lines. Figure 7 shows what NestJS does inside createApplicationContext.

1  [main.ts] --> [NestFactory]        createApplicationContext(AppModule)
2  [NestFactory] reads @Module        3 recipes: CheckoutService,
                                      PAYMENTS, SEND_EMAIL
3  [NestFactory] reads @Inject        CheckoutService needs PAYMENTS
                                      and SEND_EMAIL first
4  [NestFactory] ==> [CardProvider]   runs the PAYMENTS factory
5  [NestFactory] ==> [Send]           runs the SEND_EMAIL factory
6  [NestFactory] ==> [CheckoutService]  new CheckoutService(both)
     ~ await: createApplicationContext resolves ~
7  [main.ts] --> [CheckoutService]    app.get(...), then checkout(...)

Figure 7: you list recipes in any order; NestJS works out that the two dependencies come before the service.

Why every parameter has @Inject

Most NestJS code you’ll read writes constructor(private readonly mailer: Mailer) with no @Inject. NestJS then finds Mailer through the parameter types that tsc records. This example can’t rely on that, for two reasons:

  • PaymentProvider is a TypeScript interface, and interfaces don’t exist at run time. So tsc records its type as plain Object, and NestJS can’t tell which provider you mean.
  • tsx doesn’t record parameter types at all. “Going deeper” shows what fails without them.

So the example names a token for every parameter, as the NestJS docs on custom providers do for this case.

Prove it with a test

The service is still a class with a constructor. Save nest/checkout.service.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import { Module } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { CheckoutService, PAYMENTS, SEND_EMAIL } from "./checkout.service.ts";
import type { PaymentProvider, Send } from "../types.ts";

const log: string[] = [];
const fakePayments: PaymentProvider = {
  async charge(amountCents) {
    log.push(`charge ${amountCents}`);
    return { status: "paid", chargeId: "ch_test" };
  },
};
const fakeEmail: Send = async (to, text) => {
  log.push(`email ${to} | ${text}`);
};

test("without the container: call the constructor yourself", async () => {
  log.length = 0;
  const service = new CheckoutService(fakePayments, fakeEmail);
  const order = await service.checkout("spring", 4, "ben@example.com");
  assert.equal(order.totalCents, 4800);
  assert.deepEqual(log, ["charge 4800", "email ben@example.com | Your tickets for Songs of Spring"]);
});

test("with the container: a test module gives the fakes", async () => {
  log.length = 0;
  @Module({
    providers: [
      CheckoutService,
      { provide: PAYMENTS, useValue: fakePayments },
      { provide: SEND_EMAIL, useValue: fakeEmail },
    ],
  })
  class TestModule {}

  const app = await NestFactory.createApplicationContext(TestModule, { logger: false });
  await app.get(CheckoutService).checkout("spring", 4, "ben@example.com");
  await app.close();
  assert.deepEqual(log, ["charge 4800", "email ben@example.com | Your tickets for Songs of Spring"]);
});

Output of npx tsx --test checkout.service.test.ts, run inside nest/:

✔ without the container: call the constructor yourself (0.764167ms)
✔ with the container: a test module gives the fakes (4.949042ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

The first test needs no NestJS at all, because the DI is in the constructor and the container only fills it. The second test checks the recipes, which a plain test can’t see. Its recipes use useValue, which hands in a ready value instead of calling a factory.

When to use a container, and when to skip it

Use one when your team already builds on NestJS, because the container comes with the framework. Also consider one when the hand-written root has many dozens of objects, and adding a service means finding the right line in a long file.

Skip it in an Express or Koa app of normal size. A main.ts of 50 lines that you can read from top to bottom is easier to follow than recipes resolved at run time. And don’t add a container to make code testable, because the DI section made the code testable with no library at all.

What a container costs

  • A second decorator setting. Your NestJS code needs experimentalDecorators, which differs from the standard decorators in the rest of the language.
  • Errors move from compile time to run time. tsc checks every line of a hand-written main.ts. With a container, a missing provider or a wrong token shows up only when the app starts, and sometimes only when a method runs.
  • Wiring you can’t read in one place. Recipes spread over many @Module files. To answer “which object fills PAYMENTS?”, you search the project for the token.
  • Lock-in. Services written for one container carry its decorators and tokens. The service logic still runs without them, as the first test showed.

Inversion of Control: the framework calls you

Inversion of Control (IoC) means that a framework calls your code, instead of your code calling a library. Martin Fowler describes it in Inversion of Control. The framework holds the main flow, and your code fills in the parts it calls. Figure 8 shows two kinds of inversion side by side.

Your code in control                   Control inverted
[main.ts] --> [readline]               (Buyer) --> [Express]
  you decide when to read a line       [Express] --> [your handler]
                                         Express decides when to call you
[checkout] ==> [MailClient]            [main.ts] ==> [MailClient]
  checkout decides what it uses          the root decides; checkout receives

Figure 8: IoC moves control to someone else, either over when your code runs (top) or over what it uses (bottom).

Express is a real example. You register a handler with app.post, and Express calls it when a request matches, as its routing guide says.

Dependency Injection is the bottom row of Figure 8. The NestJS docs call DI “an inversion of control (IoC) technique”, which is why containers are also called IoC containers.

Choosing between DI, a root and a container

Figure 9 is the decision figure for this module. It starts from the code in front of you.

A function creates a client, reads process.env, or calls new Date()
  |
  v
Do you need to test it, or run it in two setups? -- no --> No pattern
  | yes                                                    needed.
  v
Hand it in: a parameter, a deps object or a constructor (DI)
  |
  v
Do several entry files create the same clients? -- no --> Create them at
  | yes                                                   the top of the
  v                                                       one entry file.
One composition root: main.ts creates everything, reads settings once
  |
  v
Is the root hard to keep in order, or is the app on NestJS already?
  | no --> Keep the hand-written root.
  | yes
  v
A container: NestJS providers and tokens

Figure 9: most code stops at DI or a hand-written root; a container is the last step.

Check yourself

  1. In one sentence, what does Dependency Injection change about a function that creates its own MailClient?
  2. Name three kinds of dependency that are not clients.
  3. What two jobs does main.ts do in this module that no other file does?
  4. Why does the NestJS example put @Inject(PAYMENTS) on its constructor parameter, even though tsc could record parameter types?
  5. How are Inversion of Control and Dependency Injection related?
Answers
  1. The function stops creating the client and receives it from its caller, so the caller (or a test) chooses which client it gets.
  2. Any three of these: settings such as an API key or an email address, the clock (new Date()), randomness (Math.random()), and data sources such as the list of orders.
  3. It reads the settings (process.env), and it creates the clients and hands them to the features.
  4. The parameter’s type is the interface PaymentProvider, which doesn’t exist at run time, so the recorded type would be Object. Also, tsx doesn’t record parameter types at all. The token tells NestJS which provider to use.
  5. IoC is the general idea that control moves out of your code to a framework or a caller. DI is one kind of IoC, where control over creating dependencies moves to the caller or the composition root.

Lab: make the evening report testable

Time: about 20 minutes. Make a folder lab/ with copies of fakes.ts, types.ts, shows.ts and tsconfig.json, and put the lab files next to them.

Every evening at 18:00, TinyTickets emails Leo the totals for that night’s show. Here is tonight-report.ts:

import { MailClient } from "./fakes.ts";
import { shows } from "./shows.ts";
import type { Order } from "./types.ts";

// Stands in for the orders table
const orders: Order[] = [
  { id: "o1", showId: "spring", buyerEmail: "ana@example.com", quantity: 2, totalCents: 2550, status: "paid" },
  { id: "o2", showId: "spring", buyerEmail: "ben@example.com", quantity: 4, totalCents: 4800, status: "paid" },
  { id: "o3", showId: "spring", buyerEmail: "chi@example.com", quantity: 1, totalCents: 1350, status: "cancelled" },
  { id: "o4", showId: "summer", buyerEmail: "chi@example.com", quantity: 1, totalCents: 1650, status: "paid" },
];

// Runs every evening at 18:00 and emails Leo the totals for tonight's show
export async function sendTonightReport(): Promise<string> {
  const today = new Date().toISOString().slice(0, 10);
  const show = [...shows.values()].find((s) => s.date === today);
  if (show === undefined) return "no show tonight";

  const paid = orders.filter((o) => o.showId === show.id && o.status === "paid");
  const tickets = paid.reduce((sum, o) => sum + o.quantity, 0);
  const cents = paid.reduce((sum, o) => sum + o.totalCents, 0);
  const text = `${show.title}: ${paid.length} paid orders, ${tickets} tickets, ${cents} cents`;

  const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
  await mail.send(process.env.REPORT_TO ?? "leo@tinytickets.example", text);
  return text;
}

console.log(await sendTonightReport());

Run today, it prints no show tonight. On March 14, 2027, it emails Songs of Spring: 2 paid orders, 6 tickets, 7350 cents.

The change request: Leo wants to see the report tested before the spring sale. Maya needs a test for the night of March 14 that she can run on any day. On staging, the report must go to Maya at maya@tinytickets.example, not to Leo.

Refactor tonight-report.ts so that this test file, tonight-report.test.ts, passes:

import { test } from "node:test";
import assert from "node:assert/strict";
import { makeTonightReport, type ReportDeps } from "./tonight-report.ts";
import type { Order } from "./types.ts";

const orders: Order[] = [
  { id: "o1", showId: "spring", buyerEmail: "ana@example.com", quantity: 2, totalCents: 2550, status: "paid" },
  { id: "o2", showId: "spring", buyerEmail: "ben@example.com", quantity: 4, totalCents: 4800, status: "paid" },
  { id: "o3", showId: "spring", buyerEmail: "chi@example.com", quantity: 1, totalCents: 1350, status: "cancelled" },
  { id: "o4", showId: "summer", buyerEmail: "chi@example.com", quantity: 1, totalCents: 1650, status: "paid" },
];

function fakeDeps(day: string, sent: string[]): ReportDeps {
  return {
    listOrders: async () => orders,
    sendEmail: async (to, text) => {
      sent.push(`${to} | ${text}`);
    },
    now: () => new Date(`${day}T18:00:00Z`),
    reportTo: "maya@tinytickets.example",
  };
}

test("on show night, the report counts only paid orders", async () => {
  const sent: string[] = [];
  const sendTonightReport = makeTonightReport(fakeDeps("2027-03-14", sent));

  await sendTonightReport();

  assert.deepEqual(sent, [
    "maya@tinytickets.example | Songs of Spring: 2 paid orders, 6 tickets, 7350 cents",
  ]);
});

test("with no show tonight, nothing is sent", async () => {
  const sent: string[] = [];
  const sendTonightReport = makeTonightReport(fakeDeps("2027-03-15", sent));

  assert.equal(await sendTonightReport(), "no show tonight");
  assert.deepEqual(sent, []);
});

Run it with npx tsx --test tonight-report.test.ts, and check types with npx tsc --noEmit. Against the current file, the test fails at once, because makeTonightReport doesn’t exist. Then write run-tonight-report.ts, the composition root for this job. It sends to Leo on live and to Maya when APP_ENV=staging.

Pause and predict: list every dependency of sendTonightReport. There are more than the one new line.

Hint 1

There are four dependencies: the orders (a data source), the mail client, the clock (new Date()), and the address in REPORT_TO. The test file names all four in ReportDeps.

Hint 2

Follow makeCheckout, so makeTonightReport(deps) returns an async function with no parameters. Inside it, replace each dependency with deps.something. now is a function, so call deps.now() each time the report runs.

Hint 3

Move the orders array to its own file, orders-data.ts, which stands in for the database. In run-tonight-report.ts, pass listOrders: async () => orders and now: () => new Date(). Then choose reportTo from process.env.APP_ENV.

Solution

tonight-report.ts:

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

export interface ReportDeps {
  listOrders: () => Promise<Order[]>;
  sendEmail: Send;
  now: () => Date;
  reportTo: string;
}

export function makeTonightReport(deps: ReportDeps): () => Promise<string> {
  return async () => {
    const today = deps.now().toISOString().slice(0, 10);
    const show = [...shows.values()].find((s) => s.date === today);
    if (show === undefined) return "no show tonight";

    const orders = await deps.listOrders();
    const paid = orders.filter((o) => o.showId === show.id && o.status === "paid");
    const tickets = paid.reduce((sum, o) => sum + o.quantity, 0);
    const cents = paid.reduce((sum, o) => sum + o.totalCents, 0);
    const text = `${show.title}: ${paid.length} paid orders, ${tickets} tickets, ${cents} cents`;

    await deps.sendEmail(deps.reportTo, text);
    return text;
  };
}

orders-data.ts:

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

// Stands in for the orders table
export const orders: Order[] = [
  { id: "o1", showId: "spring", buyerEmail: "ana@example.com", quantity: 2, totalCents: 2550, status: "paid" },
  { id: "o2", showId: "spring", buyerEmail: "ben@example.com", quantity: 4, totalCents: 4800, status: "paid" },
  { id: "o3", showId: "spring", buyerEmail: "chi@example.com", quantity: 1, totalCents: 1350, status: "cancelled" },
  { id: "o4", showId: "summer", buyerEmail: "chi@example.com", quantity: 1, totalCents: 1650, status: "paid" },
];

run-tonight-report.ts:

import { MailClient } from "./fakes.ts";
import { orders } from "./orders-data.ts";
import { makeTonightReport } from "./tonight-report.ts";

// The composition root for the evening job: settings and clients live here
const staging = process.env.APP_ENV === "staging";
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");

const sendTonightReport = makeTonightReport({
  listOrders: async () => orders,
  sendEmail: (to, text) => mail.send(to, text),
  now: () => new Date(),
  reportTo: staging ? "maya@tinytickets.example" : "leo@tinytickets.example",
});

console.log(await sendTonightReport());

Run today, npx tsx run-tonight-report.ts prints no show tonight, the same as the old file. With the clock set to 18:00 UTC on March 14, 2027, it prints:

[mail] to leo@tinytickets.example: Songs of Spring: 2 paid orders, 6 tickets, 7350 cents
Songs of Spring: 2 paid orders, 6 tickets, 7350 cents

With APP_ENV=staging, the first line starts [mail] to maya@tinytickets.example. The test passes with ℹ pass 2 and ℹ fail 0.

This solution leaves two things as they were. The report still uses the UTC date from toISOString, so near midnight it can pick the wrong day for a local show. And listOrders still returns every order for the report to filter, because a real database query belongs in Module 7.

Which pattern, if any?

Scenario A: a one-off rename script

Leo renamed the summer show. Maya wrote a script that she will run once, by hand, and then delete. Save rename-show.ts:

import { shows } from "./shows.ts";

// One-off script: Leo renamed a show. Maya runs this once, by hand.
const show = shows.get("summer");
if (show === undefined) throw new Error("no show with id summer");
show.title = "Summer Lights Festival";
console.log(`[db] renamed summer to ${show.title}`);

It prints [db] renamed summer to Summer Lights Festival. The new requirement is to email Leo the new title when the script finishes. Do you need DI, a composition root or a container?

Hint 1

Count the entry points, the tests and the setups this script will ever have.

Hint 2

Where would a composition root for this script go? Compare that place with where the code already starts.

Strong answer

No pattern. The script has one entry point, no tests and one run, so create the MailClient at the top and send at the end:

import { MailClient } from "./fakes.ts";
import { shows } from "./shows.ts";

// One-off script: Leo renamed a show. Maya runs this once, by hand.
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const show = shows.get("summer");
if (show === undefined) throw new Error("no show with id summer");
show.title = "Summer Lights Festival";
console.log(`[db] renamed summer to ${show.title}`);
await mail.send("leo@tinytickets.example", `The show is now called ${show.title}`);

Output:

[db] renamed summer to Summer Lights Festival
[mail] to leo@tinytickets.example: The show is now called Summer Lights Festival

The top of the file is already the composition root, because the client is created once, at the entry point. A deps type or a makeRename function would add lines that no test and no second setup will use. If the script later becomes a nightly job with a test, move the work into a function that receives the client.

Scenario B: the seat-map service in tests

The checkout page shows how many seats are free. Save seats-before.ts:

import { setTimeout as sleep } from "node:timers/promises";

// A fake HTTP client for the slow seat-map service
class SeatMapHttpClient {
  readonly #baseUrl: string;
  constructor(baseUrl: string) {
    this.#baseUrl = baseUrl;
  }
  async getSeatMap(showId: string, signal: AbortSignal): Promise<string[]> {
    await sleep(20, undefined, { signal });
    console.log(`[seats] GET ${this.#baseUrl}/shows/${showId}/seats`);
    return ["A1", "A2", "B7"];
  }
}

export async function freeSeatCount(showId: string): Promise<number> {
  const client = new SeatMapHttpClient("https://seats.tinytickets.example");
  const seats = await client.getSeatMap(showId, AbortSignal.timeout(2000));
  return seats.length;
}

console.log(await freeSeatCount("spring"), "free seats");

Output:

[seats] GET https://seats.tinytickets.example/shows/spring/seats
3 free seats

The new requirement has two parts. The tests for the checkout page must not call the seat-map service, which is slow and sometimes down. And staging must use https://seats-staging.tinytickets.example. Which pattern, if any?

Hint 1

Find the new line and the hard-coded setting. Both requirements touch them.

Hint 2

The course already has a contract for this client, interface SeatMapClient { getSeatMap(showId: string, signal: AbortSignal): Promise<string[]> }.

Strong answer

DI plus a composition root. freeSeatCount receives a SeatMapClient, and the root creates the real client with the base URL from a setting. seat-map.ts:

import { setTimeout as sleep } from "node:timers/promises";

export interface SeatMapClient {
  getSeatMap(showId: string, signal: AbortSignal): Promise<string[]>;
}

// A fake HTTP client for the slow seat-map service
export class SeatMapHttpClient {
  readonly #baseUrl: string;
  constructor(baseUrl: string) {
    this.#baseUrl = baseUrl;
  }
  async getSeatMap(showId: string, signal: AbortSignal): Promise<string[]> {
    await sleep(20, undefined, { signal });
    console.log(`[seats] GET ${this.#baseUrl}/shows/${showId}/seats`);
    return ["A1", "A2", "B7"];
  }
}

export async function freeSeatCount(seatMap: SeatMapClient, showId: string): Promise<number> {
  const seats = await seatMap.getSeatMap(showId, AbortSignal.timeout(2000));
  return seats.length;
}

seats-main.ts:

import { SeatMapHttpClient, freeSeatCount } from "./seat-map.ts";

// Composition root: the base URL is a setting, read here and nowhere else
const seatMap = new SeatMapHttpClient(process.env.SEATS_URL ?? "https://seats.tinytickets.example");
console.log(await freeSeatCount(seatMap, "spring"), "free seats");

npx tsx seats-main.ts prints the same two lines as before. With SEATS_URL=https://seats-staging.tinytickets.example, the first line shows the staging URL. A test passes a one-line fake, { getSeatMap: async () => ["A1", "A2"] }, and expects 2, so no request leaves the test.

The timeout stays inside freeSeatCount, because it’s a rule of this feature and is the same in every setup. A container isn’t needed for one client. Module 9 adds retries around this same client, and the root is where those wrappers go on.

Get feedback on your answer

Copy this prompt into an AI assistant, with your answer and the scenario code pasted where shown:

I am learning Dependency Injection and the composition root in TypeScript
and Node.js. Here is a scenario and my answer.

Scenario code and requirement:
<paste the scenario code and the requirement>

My answer (which pattern, if any, and my code):
<paste your answer>

Review my answer as a senior Node.js developer. Tell me:
1. Did I find every dependency, including settings and the clock?
2. Is every "new" for a client and every process.env read in one place,
   near the entry point?
3. Did I add anything this requirement does not need, such as a container,
   a deps type or an interface with one user?
4. One concrete change that would make my answer simpler or safer.
Keep the review short and use plain English.

Going deeper

You can skip this section. It covers history, near neighbors and NestJS details the main path left out.

Where the names come from

Dependency Injection is not one of the 23 patterns in the GoF book, Design Patterns (1994). Martin Fowler gave it its name in 2004, in Inversion of Control Containers and the Dependency Injection pattern. The term “composition root” comes from Mark Seemann’s article Composition Root.

Often confused with

  • Factory (Module 2). A factory decides how to create an object. DI decides who creates it and how it reaches the code that uses it. makeCheckout is both, a factory function that receives its dependencies.
  • Strategy (Module 4). A strategy is a behavior you choose per call, such as card or wallet for this buyer. DI chooses once, at startup, which object fills a slot.
  • Singleton (Module 2). The root creates one MailClient and hands it to everyone, so there is one instance. But a Singleton lets any file fetch that instance by itself, and the root doesn’t.
  • Facade (Module 3). buildApp returns one object with three methods, which looks like a Facade. A Facade hides a complex subsystem behind a simpler interface, but buildApp hides nothing, because its job is to connect.
  • Service Locator. A service locator is a shared registry that code asks for its dependencies, such as registry.get("payments"). With a locator the code pulls, and with DI the caller pushes. A locator hides what a function needs, because the needs aren’t in its parameters.

Setter injection

Fowler’s article also names a fourth way to hand in a dependency, setting a field after the object is created. That leaves a moment when the object exists without its dependency, so prefer the constructor or a parameter.

The composition root as a class

The main.ts in this module uses plain functions. A class form keeps the clients in private fields and adds a close() method. Prefer the function form, and use the class form only when the root must also close what it opened, such as database pools at shutdown (Module 7).

Lifetimes in NestJS

By default, NestJS creates a provider once and shares it with the whole app, which NestJS calls the singleton scope. A provider can also ask for a new instance per request or per consumer, as the docs on injection scopes describe. In a hand-written root, “once” means a line in main.ts, and “per request” means a factory function that the handler calls.

What fails under tsx without @Inject

tsx removes types with esbuild, a fast tool that deletes types without checking them. But esbuild does not support emitDecoratorMetadata, so it records no parameter types. The README that comes with @nestjs/core 12.5 says the same, and tells you to run such apps with a compiler that records them, such as tsc.

So under tsx, a class like Reminders with constructor(private readonly mailer: Mailer) and no @Inject gets no mailer. NestJS creates it with no arguments, and nothing fails at startup. The error, TypeError: Cannot read properties of undefined (reading 'send'), appears only when a method uses the missing mailer. Compiled by tsc with emitDecoratorMetadata, the same class receives its Mailer and runs.

Cheat sheet

Pattern or tool The problem it answers The signal in your code
Dependency Injection A test or a second setup cannot swap a client new SomeClient(...), process.env, new Date() inside business logic
Composition root Creation and settings are spread over many files The same client created in two files; process.env read in many files
Container (NestJS) A long hand-written root, or a NestJS app Dozens of services, @Injectable() already in use
Inversion of Control The same main flow is written again and again Your code runs a loop or a startup order that a framework could own
No pattern A script with one entry point and no tests One file, run once; create the client at the top
  • Receive, don’t create. A function that receives its clients, settings and clock can be tested with plain fakes.
  • One root. Only main.ts reads process.env and creates clients, so a staging setup is one condition in one file.
  • Wrappers go on in the root. withLogging was added in main.ts, and no feature file changed.
  • A container is the last step. NestJS works out the order of creation, at the price of older decorators and errors found at run time.
  • Tokens for interfaces. An interface doesn’t exist at run time, so a NestJS parameter typed with one needs @Inject(TOKEN).

Next, Module 7 turns listOrders from the lab into a Repository. The composition root then opens one database connection and hands it to every repository.

Sources