Software Architecture

Domain-Driven Design: Practical project, building a complete application from start to finish

Integrate the collection by building an order API with TypeScript, Express, Zod, and SQLite. Includes project files, domain rules, events, version control, Vitest tests, and commands to run and verify it locally.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

A store needs to stop managing orders through manual table changes. It wants to create drafts, confirm them when they contain products, and cancel those not yet confirmed. It also needs to know which confirmations were recorded, even after restarting the application.

We will build that local application: an HTTP API, a domain model, SQLite persistence, event processing, and tests. The scope is a complete educational backend for those operations, not a store with payments, user accounts, and a catalog.

The following files form a new, self-contained proposal. They do not come from the Código con Criterio repository. Their dependencies have not been installed, nor their build or tests executed during preparation of this article. Checks are included to reproduce and verify it locally, without claiming results that do not yet exist.

1. Reduced discovery: agree on what we are building

Imagine a conversation with the person managing orders:

—Does confirming mean the customer has already paid?

—In this exercise, it means the order is closed for preparation. Payment belongs to another process.

—Can we confirm an empty order?

—No. It can be saved empty as a draft but needs products before confirmation.

—What happens if someone confirms again?

—It is rejected. We do not want a new request to represent a second confirmation.

The reduced workshop produces this project-specific agreement:

  • An order starts in DRAFT and contains between zero and twenty lines.
  • Each line identifies a product through nonempty text of up to eighty characters and an integer quantity between one and one hundred.
  • The same product identifier cannot occur on two lines. Outer whitespace is removed before comparison.
  • Only DRAFT can become CONFIRMED, and it must contain at least one line.
  • Only DRAFT can become CANCELLED. An empty draft can also be canceled.
  • CONFIRMED and CANCELLED are final states for this MVP.
  • Repeated confirmation is rejected; it is not interpreted as idempotent success.
  • The persisted version detects writes based on stale state.
  • Every accepted confirmation generates an event and a queryable record in the same transaction.

These are example decisions, not universal e-commerce rules. The agreed vocabulary avoids mixing “confirmed,” “paid,” and “dispatched.”

The process can be represented as follows:

Operator -> Create order -> DRAFT
                              |
                  +-----------+-----------+
                  |                       |
          Confirm with lines           Cancel
                  |                       |
              CONFIRMED               CANCELLED
                  |
            OrderConfirmed
                  |
     Local confirmation record

We will not implement line editing, prices, payment, availability, or dispatch. A draft is created with its final lines to keep the project small. That leaves none of the promised operations incomplete.

2. Contexts and MVP decisions

We identify Sales as the order owner. Catalog would own commercial product descriptions; Inventory, availability; Billing, invoicing. This application implements only Sales: productId is a reference, not an import of external entities.

The other contexts are discovery candidates, not services we must create. We will not query their databases or pretend to know their rules. The confirmation contract we produce supports discussing a future integration without implementing imaginary consumers.

We use a structure prepared for a modular monolith because we need neither distributed deployments nor transactions. Sales responsibility justifies an explicit model; authentication, email, and other generic services are outside the exercise. We need no Shared Kernel, generic bus, or injection container to solve this operation.

The consistency decision is local and verifiable:

HTTP -> application -> Order
             |
       OrderRepository
             |
        SQLite adapter
             |
     BEGIN IMMEDIATE
       save version and state
       process OrderConfirmed
       save confirmation contract
     COMMIT

Event processing produces only local data within the transaction. It does not send email or call another system through HTTP. This avoids presenting an external effect as something SQLite could roll back.

3. Environment, installation, and structure

You need Node.js 24 and npm. We choose node:sqlite to avoid an additional native package; DatabaseSync provides a SQLite connection with synchronous operations. This keeps the example compact but blocks the JavaScript thread while working: do not extrapolate it to long queries or a highly concurrent API without evaluating alternatives. SQLite in Node.js 24.

We will use Express 5, Zod 4, TypeScript 5.9, and Vitest 4. Node 24 meets the requirements of the selected Express and Vitest branches. The linked Vitest guide corresponds to version 4 and does not assume it is the latest available. Express: installation, Vitest 4: installation.

Create a new folder:

mkdir ddd-orders-workshop
cd ddd-orders-workshop
node --version
npm --version

Copy the following files, respecting their paths. The commands do not modify any existing repository.

ddd-orders-workshop/
  package.json
  tsconfig.json
  tsconfig.check.json
  .gitignore
  src/
    main.ts
    sales/
      domain/order.ts
      application/orders.ts
      infrastructure/sqlite-orders.ts
      presentation/http.ts
  tests/
    order.test.ts
    sqlite.test.ts
    http.test.ts

package.json

{
  "name": "ddd-orders-workshop",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=24 <25" },
  "scripts": {
    "build": "tsc",
    "typecheck": "tsc -p tsconfig.check.json",
    "start": "node dist/main.js",
    "test": "vitest run"
  },
  "dependencies": { "express": "^5.1.0", "zod": "^4.0.0" },
  "devDependencies": {
    "@types/express": "^5.0.0",
    "@types/node": "^24.0.0",
    "typescript": "~5.9.3",
    "vitest": "^4.0.0"
  }
}

Ranges constrain major branches, but initial dependency resolution may change over time. npm install generates package-lock.json: keep it with the project. Subsequent installations should use npm ci to reproduce that resolution. This does not replace reviewing security advisories before reusing it in a real system.

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "rootDir": "src",
    "outDir": "dist"
  },
  "include": ["src/**/*.ts"]
}

tsconfig.check.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": { "rootDir": ".", "noEmit": true },
  "include": ["src/**/*.ts", "tests/**/*.ts"]
}

We separate compiling src from type-checking src and tests. Vitest runs tests but does not replace that static check.

.gitignore

node_modules/
dist/
data/
coverage/

4. Model: the order protects its transitions

Quantity represents a valid value, and Order contains behavior. The static create factory establishes initial state; restore reconstructs an internal snapshot without emitting new events.

We add no Domain Service because no rule needs to coordinate concepts outside the order. Applying the collection means choosing justified tools, not introducing every pattern into every file.

src/sales/domain/order.ts

export type Status = "DRAFT" | "CONFIRMED" | "CANCELLED";
export type LineInput = Readonly<{ productId: string; quantity: number }>;
export type Snapshot = Readonly<{
  id: string;
  status: Status;
  lines: readonly LineInput[];
  version: number;
}>;
export type OrderConfirmed = Readonly<{
  type: "OrderConfirmed";
  eventId: string;
  orderId: string;
  occurredAt: string;
}>;

export class RuleViolation extends Error {}

export class Quantity {
  readonly #value: number;
  constructor(value: number) {
    if (!Number.isSafeInteger(value) || value < 1 || value > 100) {
      throw new RuleViolation("INVALID_QUANTITY");
    }
    this.#value = value;
  }
  get value(): number { return this.#value; }
}

export class Order {
  #status: Status;
  #version: number;
  readonly #lines: readonly LineInput[];
  #events: OrderConfirmed[] = [];

  private constructor(snapshot: Snapshot) {
    this.#status = snapshot.status;
    this.#version = snapshot.version;
    this.id = snapshot.id;
    if (snapshot.lines.length > 20) {
      throw new RuleViolation("TOO_MANY_LINES");
    }
    const seen = new Set<string>();
    this.#lines = snapshot.lines.map((line) => {
      const productId = line.productId.trim();
      if (!productId || productId.length > 80 || seen.has(productId)) {
        throw new RuleViolation("INVALID_OR_DUPLICATE_PRODUCT");
      }
      seen.add(productId);
      return Object.freeze({
        productId,
        quantity: new Quantity(line.quantity).value,
      });
    });
  }

  readonly id: string;

  static create(id: string, lines: readonly LineInput[]): Order {
    return new Order({ id, lines, status: "DRAFT", version: 0 });
  }

  // Solo para snapshots internos leídos desde nuestra persistencia.
  static restore(snapshot: Snapshot): Order { return new Order(snapshot); }

  confirm(eventId: string, occurredAt: string): void {
    if (this.#status !== "DRAFT") {
      throw new RuleViolation("ORDER_NOT_DRAFT");
    }
    if (this.#lines.length === 0) {
      throw new RuleViolation("ORDER_EMPTY");
    }
    this.#status = "CONFIRMED";
    this.#events.push(Object.freeze({
      type: "OrderConfirmed",
      eventId,
      orderId: this.id,
      occurredAt,
    }));
  }

  cancel(): void {
    if (this.#status !== "DRAFT") {
      throw new RuleViolation("ORDER_NOT_DRAFT");
    }
    this.#status = "CANCELLED";
  }

  snapshot(): Snapshot {
    return {
      id: this.id,
      status: this.#status,
      version: this.#version,
      lines: this.#lines.map((line) => ({ ...line })),
    };
  }

  pendingEvents(): readonly OrderConfirmed[] { return [...this.#events]; }

  // El adaptador lo llama únicamente después de COMMIT.
  acknowledgePersistence(): void {
    this.#version += 1;
    this.#events = [];
  }
}

Getters and copies allow queries without sharing the internal array. State uses JavaScript private fields. acknowledgePersistence is an internal adapter protocol: it is not exposed as an HTTP operation or a substitute for a business method.

Before saving, version is zero. Initial persistence raises it to one; every accepted write increments it. restore trusts data written by our own application. A file importer or administrative tool would need its own snapshot validation.

The product identifier has an eighty-character maximum in both HTTP and the domain. Transport protects request shape; the domain retains that rule even when called from another adapter.

5. Use cases and integration contract

To reduce small files, we group use cases in Orders. Each method coordinates one operation without reproducing state conditions. A larger project could separate CreateOrder, ConfirmOrder, and CancelOrder without changing rules.

The internal OrderConfirmed event is converted through a handler into sales.order-confirmed.v1. The contract contains identifier, date, and confirmed order. It neither exports the aggregate nor automatically turns every field into a public API.

src/sales/application/orders.ts

import {
  Order, type LineInput, type OrderConfirmed, type Snapshot,
} from "../domain/order.js";

export class NotFound extends Error {}
export class Conflict extends Error {}

export type ConfirmationV1 = Readonly<{
  id: string;
  type: "sales.order-confirmed.v1";
  occurredAt: string;
  data: Readonly<{ orderId: string }>;
}>;

// Contrato público deliberadamente separado del evento interno.
export function handleOrderConfirmed(event: OrderConfirmed): ConfirmationV1 {
  return {
    id: event.eventId,
    type: "sales.order-confirmed.v1",
    occurredAt: event.occurredAt,
    data: { orderId: event.orderId },
  };
}

export interface OrderRepository {
  find(id: string): Order | null;
  save(order: Order): void;
  confirmations(id: string): readonly ConfirmationV1[];
}

export class Orders {
  constructor(
    private readonly repository: OrderRepository,
    private readonly newId: () => string,
    private readonly now: () => string,
  ) {}

  create(lines: readonly LineInput[]): Snapshot {
    const order = Order.create(this.newId(), lines);
    this.repository.save(order);
    return order.snapshot();
  }

  private require(id: string): Order {
    const order = this.repository.find(id);
    if (!order) throw new NotFound("ORDER_NOT_FOUND");
    return order;
  }

  get(id: string): Snapshot { return this.require(id).snapshot(); }

  confirm(id: string): Snapshot {
    const order = this.require(id);
    order.confirm(this.newId(), this.now());
    this.repository.save(order);
    return order.snapshot();
  }

  cancel(id: string): Snapshot {
    const order = this.require(id);
    order.cancel();
    this.repository.save(order);
    return order.snapshot();
  }

  confirmations(id: string): readonly ConfirmationV1[] {
    this.require(id);
    return this.repository.confirmations(id);
  }
}

The clock and identifier generator are injected externally. The domain receives those values and need not import Node tools.

The confirmations read is in the same port to keep the exercise short. With more queries, it could be separated into a read port. Doing so here would change neither behavior nor consistency.

6. Real persistence and atomic event processing

We save the snapshot as JSON and maintain a version column for conditional writing. This is an educational decision: it simplifies reconstruction at the cost of limiting SQL queries over lines. An application with complex searches or reports might need normalized tables.

src/sales/infrastructure/sqlite-orders.ts

import { DatabaseSync } from "node:sqlite";
import { Order, type Snapshot } from "../domain/order.js";
import {
  Conflict, handleOrderConfirmed,
  type ConfirmationV1, type OrderRepository,
} from "../application/orders.js";

export function initialize(db: DatabaseSync): void {
  db.exec(`
    PRAGMA foreign_keys = ON;
    PRAGMA busy_timeout = 3000;
    CREATE TABLE IF NOT EXISTS orders (
      id TEXT PRIMARY KEY,
      snapshot TEXT NOT NULL,
      version INTEGER NOT NULL CHECK(version >= 1)
    );
    CREATE TABLE IF NOT EXISTS confirmations (
      id TEXT PRIMARY KEY,
      order_id TEXT NOT NULL REFERENCES orders(id),
      payload TEXT NOT NULL
    );
  `);
}

export class SqliteOrders implements OrderRepository {
  constructor(private readonly db: DatabaseSync) {}

  find(id: string): Order | null {
    const row = this.db.prepare(
      "SELECT snapshot FROM orders WHERE id = ?",
    ).get(id);
    if (!row) return null;
    return Order.restore(JSON.parse(String(row.snapshot)) as Snapshot);
  }

  save(order: Order): void {
    const snapshot = order.snapshot();
    const next = { ...snapshot, version: snapshot.version + 1 };
    const events = order.pendingEvents();
    this.db.exec("BEGIN IMMEDIATE");
    try {
      if (snapshot.version === 0) {
        const result = this.db.prepare(
          "INSERT OR IGNORE INTO orders(id, snapshot, version) VALUES(?, ?, 1)",
        ).run(snapshot.id, JSON.stringify(next));
        if (Number(result.changes) !== 1) {
          throw new Conflict("ORDER_ALREADY_EXISTS");
        }
      } else {
        const result = this.db.prepare(
          "UPDATE orders SET snapshot = ?, version = ? WHERE id = ? AND version = ?",
        ).run(JSON.stringify(next), next.version, snapshot.id, snapshot.version);
        if (Number(result.changes) !== 1) {
          throw new Conflict("ORDER_VERSION_CONFLICT");
        }
      }

      for (const event of events) {
        const contract = handleOrderConfirmed(event);
        this.db.prepare(
          "INSERT INTO confirmations(id, order_id, payload) VALUES(?, ?, ?)",
        ).run(contract.id, snapshot.id, JSON.stringify(contract));
      }
      this.db.exec("COMMIT");
    } catch (error) {
      this.db.exec("ROLLBACK");
      throw error;
    }
    order.acknowledgePersistence();
  }

  confirmations(id: string): readonly ConfirmationV1[] {
    return this.db.prepare(
      "SELECT payload FROM confirmations WHERE order_id = ? ORDER BY rowid",
    ).all(id).map((row) =>
      JSON.parse(String(row.payload)) as ConfirmationV1,
    );
  }
}

The adapter implements the application contract and knows SQLite. Order does not know SQL. Outer composition decides to use this implementation.

If two copies load version 1, only one can update it to 2. The second write affects zero rows and is rejected with a conflict. BEGIN IMMEDIATE helps organize local writing; it does not replace the version condition.

The handler executes after updating the order and before COMMIT. If inserting its result fails, ROLLBACK also reverses the state change. Pending events are cleared only after committing the transaction.

The confirmations table retains the versioned contract and allows querying it. It is not a delivery system to other contexts: it has no consumer, receipt acknowledgment, or retries. Nor are we reconstructing orders from events, so this is not Event Sourcing. If an external integration appeared, its delivery and reliability would need to be designed as an additional capability.

7. HTTP: validate and translate results

Zod validates HTTP input through safeParse, allowing success and error to be distinguished without throwing an exception for every invalid request. That does not move aggregate rules into the schema. Zod basics.

The exercise contract assigns 400 to invalid input, 404 to nonexistent orders, 409 to version conflicts, and 422 to violated order rules. These are documented decisions for this API.

src/sales/presentation/http.ts

import express, {
  type ErrorRequestHandler, type RequestHandler,
} from "express";
import { z } from "zod";
import { Conflict, NotFound, Orders } from "../application/orders.js";
import { RuleViolation } from "../domain/order.js";

const createBody = z.object({
  lines: z.array(z.object({
    productId: z.string().trim().min(1).max(80),
    quantity: z.number().int().min(1).max(100),
  }).strict()).max(20),
}).strict();
const params = z.object({ id: z.string().uuid() });

export function createApp(orders: Orders) {
  const app = express();
  app.disable("x-powered-by");
  app.use(express.json({ limit: "16kb" }));

  app.post("/orders", (request, response) => {
    const result = createBody.safeParse(request.body);
    if (!result.success) {
      response.status(400).json({ error: "INVALID_BODY" });
      return;
    }
    const order = orders.create(result.data.lines);
    response.location("/orders/" + order.id).status(201).json(order);
  });

  const validId: RequestHandler = (request, response, next) => {
    if (!params.safeParse(request.params).success) {
      response.status(400).json({ error: "INVALID_ID" });
      return;
    }
    next();
  };

  app.get("/orders/:id", validId, (request, response) => {
    response.json(orders.get(String(request.params.id)));
  });
  app.post("/orders/:id/confirm", validId, (request, response) => {
    response.json(orders.confirm(String(request.params.id)));
  });
  app.post("/orders/:id/cancel", validId, (request, response) => {
    response.json(orders.cancel(String(request.params.id)));
  });
  app.get("/orders/:id/confirmations", validId, (request, response) => {
    response.json(orders.confirmations(String(request.params.id)));
  });

  app.use((_request, response) => {
    response.status(404).json({ error: "ROUTE_NOT_FOUND" });
  });

  const errors: ErrorRequestHandler = (error, _request, response, _next) => {
    if (error instanceof NotFound) {
      response.status(404).json({ error: error.message });
    } else if (error instanceof Conflict) {
      response.status(409).json({ error: error.message });
    } else if (error instanceof RuleViolation) {
      response.status(422).json({ error: error.message });
    } else if (error?.type === "entity.parse.failed") {
      response.status(400).json({ error: "INVALID_JSON" });
    } else if (error?.type === "entity.too.large") {
      response.status(413).json({ error: "BODY_TOO_LARGE" });
    } else {
      console.error("Unhandled request error");
      response.status(500).json({ error: "INTERNAL_ERROR" });
    }
  };
  app.use(errors);
  return app;
}

Confirmation and cancellation routes do not receive arbitrary order changes; intent is expressed in the operation. A client cannot send status to bypass the aggregate.

This local server implements neither users nor authorization. It will listen only on 127.0.0.1: do not publish it or make it externally accessible as though it were a production API. The absence of those capabilities is part of local scope, not a recommendation for real applications.

8. Manual composition and startup

src/main.ts

import { mkdirSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { DatabaseSync } from "node:sqlite";
import { Orders } from "./sales/application/orders.js";
import { initialize, SqliteOrders } from "./sales/infrastructure/sqlite-orders.js";
import { createApp } from "./sales/presentation/http.js";

mkdirSync("data", { recursive: true });
const db = new DatabaseSync("data/orders.sqlite");
initialize(db);
const orders = new Orders(
  new SqliteOrders(db), randomUUID, () => new Date().toISOString(),
);
const server = createApp(orders).listen(3000, "127.0.0.1", () => {
  console.log("Orders API: http://127.0.0.1:3000");
});
for (const signal of ["SIGINT", "SIGTERM"] as const) {
  process.once(signal, () => {
    server.close(() => {
      db.close();
      process.exit(0);
    });
  });
}

The connection opens once and closes when the server stops. The database is at data/orders.sqlite relative to the folder from which you start. Always run npm start at project root to use the same file.

After copying every file:

npm install
npm run typecheck
npm test
npm run build
npm start

The first line downloads dependencies into this new folder. It was not executed while preparing the article. On error, stop and review output before continuing; commands are shown separately so you can identify it.

If your build does not recognize node:sqlite, check you are running Node 24 and installation resolved @types/node from branch 24. If port 3000 is occupied, stop the previous process or explicitly change the example's port.

9. Domain, persistence, and HTTP walkthrough tests

The following suites are complete project files. Their results must be obtained by running npm test in your environment; they are not presented here as passing tests.

tests/order.test.ts

import { describe, expect, it } from "vitest";
import { Order, Quantity } from "../src/sales/domain/order.js";

const line = { productId: "book-1", quantity: 2 };
const eventId = "event-1";
const time = "2026-10-23T12:00:00.000Z";

describe("Order", () => {
  it("crea DRAFT, confirma y registra un evento", () => {
    const order = Order.create("order-1", [line]);
    expect(order.snapshot().status).toBe("DRAFT");
    order.confirm(eventId, time);
    expect(order.snapshot().status).toBe("CONFIRMED");
    expect(order.pendingEvents()).toEqual([{
      type: "OrderConfirmed", eventId, orderId: "order-1", occurredAt: time,
    }]);
  });

  it("rechaza vacío sin cambiar estado ni emitir eventos", () => {
    const order = Order.create("order-1", []);
    expect(() => order.confirm(eventId, time)).toThrow("ORDER_EMPTY");
    expect(order.snapshot().status).toBe("DRAFT");
    expect(order.pendingEvents()).toEqual([]);
  });

  it("rechaza repetición sin duplicar eventos", () => {
    const order = Order.create("order-1", [line]);
    order.confirm(eventId, time);
    expect(() => order.confirm("event-2", time)).toThrow("ORDER_NOT_DRAFT");
    expect(order.pendingEvents()).toHaveLength(1);
  });

  it("no permite confirmar un pedido cancelado", () => {
    const order = Order.create("order-1", [line]);
    order.cancel();
    expect(() => order.confirm(eventId, time)).toThrow("ORDER_NOT_DRAFT");
    expect(order.snapshot().status).toBe("CANCELLED");
  });

  it("solo permite cancelar DRAFT", () => {
    const order = Order.create("order-1", [line]);
    order.confirm(eventId, time);
    expect(() => order.cancel()).toThrow("ORDER_NOT_DRAFT");
    const cancelled = Order.create("order-2", []);
    cancelled.cancel();
    expect(() => cancelled.cancel()).toThrow("ORDER_NOT_DRAFT");
  });

  it.each([0, -1, 1.5, 101, NaN])("rechaza cantidad %s", (value) => {
    expect(() => new Quantity(value)).toThrow("INVALID_QUANTITY");
  });

  it("acepta los extremos válidos", () => {
    expect(new Quantity(1).value).toBe(1);
    expect(new Quantity(100).value).toBe(100);
  });

  it("rechaza productos vacíos, repetidos y más de 20 líneas", () => {
    expect(() => Order.create("a", [{ ...line, productId: " " }]))
      .toThrow("INVALID_OR_DUPLICATE_PRODUCT");
    expect(() => Order.create("a", [{ ...line, productId: "x".repeat(81) }]))
      .toThrow("INVALID_OR_DUPLICATE_PRODUCT");
    expect(() => Order.create("a", [line, line]))
      .toThrow("INVALID_OR_DUPLICATE_PRODUCT");
    expect(() => Order.create("a", Array.from({ length: 21 }, (_, i) => ({
      productId: "p-" + i, quantity: 1,
    })))).toThrow("TOO_MANY_LINES");
  });

  it("no expone referencias mutables de las líneas", () => {
    const input = [{ ...line }];
    const order = Order.create("a", input);
    input[0].quantity = 99;
    const snapshot = order.snapshot();
    expect(snapshot.lines[0].quantity).toBe(2);
    expect(order.snapshot().lines[0].quantity).toBe(2);
  });
});

These tests distinguish rules: empty, repetition, canceled, quantities, and reference protection. Every rejection preserves prior state and prevents additional events.

tests/sqlite.test.ts

import { DatabaseSync } from "node:sqlite";
import { afterEach, beforeEach, expect, it } from "vitest";
import { Order } from "../src/sales/domain/order.js";
import { initialize, SqliteOrders } from "../src/sales/infrastructure/sqlite-orders.js";

let db: DatabaseSync;
let repository: SqliteOrders;
beforeEach(() => {
  db = new DatabaseSync(":memory:");
  initialize(db);
  repository = new SqliteOrders(db);
});
afterEach(() => db.close());

it("persiste estado y contrato, y limpia eventos tras COMMIT", () => {
  const order = Order.create("o-1", [{ productId: "p-1", quantity: 1 }]);
  repository.save(order);
  order.confirm("e-1", "2026-10-23T12:00:00.000Z");
  repository.save(order);
  expect(repository.find("o-1")?.snapshot().status).toBe("CONFIRMED");
  expect(repository.confirmations("o-1")).toEqual([{
    id: "e-1",
    type: "sales.order-confirmed.v1",
    occurredAt: "2026-10-23T12:00:00.000Z",
    data: { orderId: "o-1" },
  }]);
  expect(order.pendingEvents()).toEqual([]);
});

it("rechaza un escritor con versión obsoleta", () => {
  repository.save(Order.create("o-1", [{ productId: "p-1", quantity: 1 }]));
  const first = repository.find("o-1")!;
  const stale = repository.find("o-1")!;
  first.confirm("e-1", "2026-10-23T12:00:00.000Z");
  repository.save(first);
  stale.cancel();
  expect(() => repository.save(stale)).toThrow("ORDER_VERSION_CONFLICT");
  expect(repository.find("o-1")?.snapshot().status).toBe("CONFIRMED");
  expect(repository.confirmations("o-1")).toHaveLength(1);
});

it("revierte el estado si falla el procesamiento del evento", () => {
  const order = Order.create("o-1", [{ productId: "p-1", quantity: 1 }]);
  repository.save(order);
  db.exec(`
    CREATE TRIGGER reject_confirmation BEFORE INSERT ON confirmations
    BEGIN SELECT RAISE(ABORT, 'TEST_FAILURE'); END;
  `);
  order.confirm("e-1", "2026-10-23T12:00:00.000Z");
  expect(() => repository.save(order)).toThrow("TEST_FAILURE");
  expect(repository.find("o-1")?.snapshot().status).toBe("DRAFT");
  expect(repository.confirmations("o-1")).toEqual([]);
  expect(order.pendingEvents()).toHaveLength(1);
});

We use real in-memory SQLite, not a mocked repository. The conflict test loads two independent aggregates. The trigger test causes a controlled failure to check that state does not remain confirmed without its record. Each test creates and closes its own connection.

The in-memory instance is disposable, but the adapter is the same one used with a file on the server. Persistence after restart will also be checked through HTTP.

tests/http.test.ts

import { randomUUID } from "node:crypto";
import { once } from "node:events";
import type { Server } from "node:http";
import { DatabaseSync } from "node:sqlite";
import type { AddressInfo } from "node:net";
import { afterEach, beforeEach, expect, it } from "vitest";
import { Orders } from "../src/sales/application/orders.js";
import { initialize, SqliteOrders } from "../src/sales/infrastructure/sqlite-orders.js";
import { createApp } from "../src/sales/presentation/http.js";

let db: DatabaseSync;
let server: Server;
let origin: string;
beforeEach(async () => {
  db = new DatabaseSync(":memory:");
  initialize(db);
  const orders = new Orders(
    new SqliteOrders(db), randomUUID, () => "2026-10-23T12:00:00.000Z",
  );
  server = createApp(orders).listen(0, "127.0.0.1");
  await once(server, "listening");
  origin = "http://127.0.0.1:" + (server.address() as AddressInfo).port;
});
afterEach(async () => {
  await new Promise<void>((resolve, reject) => {
    server.close((error) => error ? reject(error) : resolve());
    server.closeAllConnections();
  });
  db.close();
});

function post(path: string, body?: unknown) {
  return fetch(origin + path, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
}

it("recorre HTTP, dominio, SQLite y consulta de confirmaciones", async () => {
  const created = await post("/orders", {
    lines: [{ productId: "book-1", quantity: 2 }],
  });
  expect(created.status).toBe(201);
  const order = await created.json() as { id: string };
  const confirmed = await post("/orders/" + order.id + "/confirm");
  expect(confirmed.status).toBe(200);
  expect((await confirmed.json()).status).toBe("CONFIRMED");
  const repeated = await post("/orders/" + order.id + "/confirm");
  expect(repeated.status).toBe(422);
  expect(await repeated.json()).toEqual({ error: "ORDER_NOT_DRAFT" });
  const events = await fetch(origin + "/orders/" + order.id + "/confirmations");
  expect((await events.json())).toHaveLength(1);
});

it("rechaza JSON inválido, cantidades inválidas e identificadores inválidos", async () => {
  const malformed = await fetch(origin + "/orders", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: "{",
  });
  expect(malformed.status).toBe(400);
  expect((await post("/orders", {
    lines: [{ productId: "p", quantity: 0 }],
  })).status).toBe(400);
  expect((await fetch(origin + "/orders/not-a-uuid")).status).toBe(400);
  expect((await fetch(origin + "/orders/" + randomUUID())).status).toBe(404);
});

it("rechaza vacío y permite cancelar un borrador", async () => {
  const created = await post("/orders", { lines: [] });
  const order = await created.json() as { id: string };
  expect((await post("/orders/" + order.id + "/confirm")).status).toBe(422);
  const cancelled = await post("/orders/" + order.id + "/cancel");
  expect((await cancelled.json()).status).toBe("CANCELLED");
  expect((await post("/orders/" + order.id + "/confirm")).status).toBe(422);
});

These tests open a system-assigned local port, send real requests, and verify responses. Upon completion, they close server and connection. They require neither an external service nor a shared database.

10. Test manually and check persistence

With npm start active, open another terminal. Use curl in Bash or curl.exe in PowerShell to avoid alias differences.

First create an order:

curl -i -X POST http://127.0.0.1:3000/orders \
  -H "Content-Type: application/json" \
  --data '{"lines":[{"productId":"book-1","quantity":2}]}'

The expected response is 201 with a body of this shape. The identifier is generated on each execution:

{
  "id": "IDENTIFICADOR_GENERADO",
  "status": "DRAFT",
  "version": 1,
  "lines": [{ "productId": "book-1", "quantity": 2 }]
}

The following commands use ID as a placeholder: replace it with the actual UUID, without additional braces.

curl -i -X POST http://127.0.0.1:3000/orders/ID/confirm
curl -i http://127.0.0.1:3000/orders/ID
curl -i http://127.0.0.1:3000/orders/ID/confirmations

Confirmation should return 200, status CONFIRMED, and version 2. Querying confirmations returns a one-element array:

[
  {
    "id": "IDENTIFICADOR_DEL_EVENTO",
    "type": "sales.order-confirmed.v1",
    "occurredAt": "FECHA_ISO_GENERADA",
    "data": { "orderId": "IDENTIFICADOR_DEL_PEDIDO" }
  }
]

Repeat confirmation: expect 422 and ORDER_NOT_DRAFT. Query confirmations again: there must still be only one. The order's version must not increase.

To test cancellation, create another draft and run:

curl -i -X POST http://127.0.0.1:3000/orders/ID/cancel

Expect 200 and CANCELLED. Trying to confirm it returns 422. A draft created with empty lines is saved, but confirming it returns ORDER_EMPTY.

Stop the server with Ctrl+C and run npm start again from the same folder. Query the first UUID: state, version, and confirmation must remain available. Do not delete the database for this check.

In PowerShell, you can also create the order and capture its identifier without copying manually:

$createdOrder = Invoke-RestMethod -Method Post `
  -Uri "http://127.0.0.1:3000/orders" `
  -ContentType "application/json" `
  -Body '{"lines":[{"productId":"book-1","quantity":2}]}'

Invoke-RestMethod -Method Post `
  -Uri "http://127.0.0.1:3000/orders/$($createdOrder.id)/confirm"

Invoke-RestMethod `
  -Uri "http://127.0.0.1:3000/orders/$($createdOrder.id)/confirmations"

No simulated outputs are offered as actual results: the preceding states are expectations your execution must confirm.

11. Document and work with AI on the project

Keep this article or its instructions in README.md, and record scope decisions alongside code. At minimum, document section 1 rules, commands, port, database location, HTTP contract, repeated-confirmation policy, and limitations.

An initial agent task could be:

Inspect this project without modifying it.
Relate each order rule to its method and test.
Confirm import direction and list README decisions
not represented in code.
Do not add infrastructure or new rules.
Return evidence with paths and open questions.

For a subsequent review:

Review order confirmation.
Check that a stale-version write fails,
that the event is saved in the same transaction, and that
a rejected confirmation adds no records.
Also examine error handling and HTTP limits.
Do not claim test results you have not executed.
Do not modify dependencies or publish the application.

And to verify work reproducibly:

Read existing scripts and run typecheck, test, and build
if the environment is authorized and ready.
Report each command's actual result and limitations.
If anything fails, propose the minimal correction before
expanding scope. Preserve others' changes.

The human owner must validate that rules still represent the business. Code passing its tests does not demonstrate those decisions are correct for another store.

12. What to reuse and change in other scenarios

On an educational platform, the transition pattern may serve enrollment. However, “completed” could depend on passed activities. Do not copy the order's “contains a line” rule or cancellation policy: define educational evidence and boundaries of their own.

In logistics, confirming preparation could depend on an inventory reservation. Our project makes no such reservation, and an external HTTP call would not be included in COMMIT. Before adding it, coordination, failures, and responsibilities must be agreed.

For a personal agenda without relevant rules, direct CRUD may suffice. This project's separation is justified by transitions, rejections, consistency, and tests; repeating its structure for an auxiliary table without behavior can add work without benefit.

13. Review exercises, with solutions

Essential features are already implemented. These exercises help check your understanding of their limits without leaving mandatory steps pending.

  1. Two operators load the same draft. One confirms and the other cancels. What prevents the last from silently overwriting the first?
  2. The handler starts sending email before COMMIT. Then the transaction fails. What inconsistency appears?
  3. A client sends quantity equal to zero. Another internal process directly calls Order.create with that quantity. Where must each input be rejected?

Reasoned solutions

1. The expected version in UPDATE's WHERE. A stale copy affects no rows and generates ORDER_VERSION_CONFLICT. The second operator must query again and decide using the new state; a business operation is not blindly retried.

2. The recipient could receive a confirmation the database eventually rolled back. That is why the current handler only transforms and records local data. Actual sending requires another delivery design; merely moving an await inside the transaction is insufficient.

3. HTTP returns 400 when Zod fails. The internal call must also fail through Quantity. The transport schema protects the input contract, and the domain maintains its rule even without HTTP.

Close the collection by building with judgment

The walkthrough produced a small application with complete behavior: validated input, aggregate, use cases, repository, SQLite, processed event, query, and tests. It also left visible decisions: one implemented context, one process, local transaction, and no invented distributed dependency.

Its production boundary is explicit: identity, authorization, operations, and controls appropriate to a real deployment are missing. Its local purpose is covered by the tutorial's files and operations, and verification depends on running commands and reviewing their results.

DDD supplied language and rules; engineering connected contracts, persistence, and tests; AI can help inspect and review those decisions. Professional judgment means checking all three still describe the same business.

Loading conversation…

Keep learning