A toolkit for Domain-Driven Design in TypeScript.
npm install ddd-kitA small collection of sharp, focused tools for taming complex business logic in TypeScript. This isn't a framework; it's a set of patterns, inspired by the Domain-Driven Design (DDD) philosophy, to help you build robust, maintainable, and testable applications.
This kit is built on a few core beliefs: your domain logic is your most valuable asset, persistence is a detail, and testability is a core feature, not an afterthought.
In small, fast-moving teams, our code should directly model the business domain, using the same terminology our experts use. This creates a Ubiquitous Language that bridges the gap between technical implementation and business reality.
---
This kit provides a set of composable primitives to structure your application:
* AggregateRoot: A base class for your domain models that guards business rules (invariants) and manages state changes.
* ICommand & CommandHandler: A pattern to encapsulate every business operation into a clean, transactional pipeline (load -> execute -> save).
* Result: A simple ok or err wrapper to handle outcomes without throwing exceptions.
* UnitOfWork: An abstraction to ensure that all database operations for a command succeed or fail together (atomicity).
* AggregateRepository: A generic port for loading and saving your aggregates, decoupling your domain from the database.
* withIdempotency: A wrapper to make your command handlers safe to retry, preventing duplicate operations.
* HTTP Helpers: Utilities (makeRequestHandler, respond) to standardize auth, validation, and response formatting at the API edge.
---
Here's a glimpse of how the pieces fit together.
1. Define a rule and a state transition in your Aggregate:
``typescript
class Order extends AggregateRoot {
// The command method makes a decision.
cancel(reason: string) {
if (this.status === 'SHIPPED') {
throw new DomainInvariantError('Cannot cancel a shipped order.');
}
// It raises an event, but doesn't change state itself.
this.raise({ type: 'OrderCancelled', data: { orderId: this.id, reason } });
}
// The apply method enacts the state change.
protected apply(event: DomainEvent): void {
if (event.type === 'OrderCancelled') {
this.status = 'CANCELLED';
}
}
}
`
2. Create a Command for the use case:
`typescript`
class CancelOrderCommand implements ICommand<{ reason: string }, { ok: boolean }, Order> {
** execute(payload: { reason: string }, aggregate: Order) {
// The command calls the aggregate's public method.
aggregate.cancel(payload.reason);
return ok({ aggregate, response: { ok: true }, events: aggregate.pullEvents() });
}
}
3. The CommandHandler runs the operation in a transaction:
`typescript
const handler = new OrderCommandHandler(/ ...dependencies... /);
// This entire operation is atomic and safe.
const result = await handler.execute('cancel-order', {
aggregateId: 'order_123',
payload: { reason: 'Customer changed their mind.' },
});
`
---
ddd-kit uses a "Raise/Apply" pattern within its AggregateRoot to keep your business logic pure and persistence-agnostic.
- Command Methods raise Events: A public method like cancel() validates the request and raises an event describing what should happen. It doesn't change the state itself.apply()
- The Method Changes State: A single, protected apply() method is the only place state can be mutated. It acts like a reducer, changing state based on the event that was raised.
This simple but powerful pattern means the same domain model works seamlessly whether you're using:
- CRUD: Rehydrating from a database row and saving the full, updated state.
- Event Sourcing: Rehydrating by replaying an event history and saving only the new event.
Your core business logic remains identical, completely decoupled from the infrastructure.
---
- 00 - Overview: Start here for the core philosophy.
- 01 - The Domain Layer: Learn about Aggregates, Entities, and guarding invariants.
- 02 - The Application Layer: Master the Command and Command Handler patterns.
- 03 - The Infrastructure Layer: Understand how to persist your aggregates with Repositories and the Unit of Work.
- 04 - The Interface Layer: Connect your core logic to the web with our HTTP helpers.
- 05 - Idempotency: Make your API robust and safe to retry.
Event Sourcing Support: While the AggregateRoot is already capable of producing domain events, we will be introducing an AbstractEsRepository`. This will provide a clear pattern for teams who want to adopt an event-sourcing persistence strategy without changing their domain logic.
Read-Side (CQRS) Helpers: So far, we've focused heavily on the "Command" side of CQRS—making sure writes are safe, transactional, and clear. The next major focus will be on the "Query" side. We plan to add helpers and patterns for building efficient read models through projections, materialized views, and dedicated query handlers.