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.
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.
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.
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.
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.
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, typeSnapshot } from"../domain/order.js";
import {
Conflict, handleOrderConfirmed,
typeConfirmationV1, typeOrderRepository,
} from"../application/orders.js";
exportfunctioninitialize(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
);
`);
}
exportclassSqliteOrdersimplementsOrderRepository {
constructor(privatereadonlydb: DatabaseSync) {}
find(id: string): Order | null {
const row = this.db.prepare(
"SELECT snapshot FROM orders WHERE id = ?",
).get(id);
if (!row) returnnull;
returnOrder.restore(JSON.parse(String(row.snapshot)) asSnapshot);
}
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) {
thrownewConflict("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) {
thrownewConflict("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): readonlyConfirmationV1[] {
returnthis.db.prepare(
"SELECT payload FROM confirmations WHERE order_id = ? ORDER BY rowid",
).all(id).map((row) =>JSON.parse(String(row.payload)) asConfirmationV1,
);
}
}
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.
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.
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.
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";
letdb: DatabaseSync;
letrepository: SqliteOrders;
beforeEach(() => {
db = newDatabaseSync(":memory:");
initialize(db);
repository = newSqliteOrders(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.
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.
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:
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.
Two operators load the same draft. One confirms and the other cancels. What prevents the last from silently overwriting the first?
The handler starts sending email before COMMIT. Then the transaction fails. What inconsistency appears?
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.
Learn to guide AI agents with business rules, context boundaries, and verifiable criteria. A TypeScript case shows how to prepare instructions, protect Order, design tests, and review changes without delegating architectural judgment.
Compare a modular monolith with separating Sales, Payments, and Inventory. Design contracts in TypeScript and Express and understand partial failures, eventual consistency, idempotency, Outbox, and Sagas without introducing complex infrastructure.
Refactor order confirmation from a coupled controller into Order, a use case, a port, and adapters. Learn the dependency rule, manual composition, and tests without infrastructure, using TypeScript and Express.