DDD and CQRS in NestJS Without the Ceremony
· Đorđije Lazarević · 3 min read
Domain-Driven Design and CQRS have a reputation for turning a simple feature into fifteen files. That happens when the patterns are applied everywhere and all at once. Used selectively, they make complex modules easier to change, and NestJS has good support for them in @nestjs/cqrs.
When it pays off
- The module has real business rules: pricing, validity periods, approvals, limits that depend on other data.
- Reads and writes look very different. The screen needs a joined, filtered view; the write changes one aggregate.
- Several entry points change the same data: the API, an import job, a scheduled task.
For plain CRUD (a settings page, a list of tags) a controller and a service are still the right tool. I mix both styles in one codebase without problems.
The write side: a command and its handler
A command is a plain object that describes an intent. The handler loads the aggregate, lets it apply the rules, and saves it.
export class UpdatePriceListCommand {
constructor(
public readonly priceListId: string,
public readonly items: { materialId: string; pricePerTon: number }[],
) {}
}
@CommandHandler(UpdatePriceListCommand)
export class UpdatePriceListHandler implements ICommandHandler<UpdatePriceListCommand> {
constructor(private readonly priceLists: PriceListRepository) {}
async execute({ priceListId, items }: UpdatePriceListCommand): Promise<void> {
const priceList = await this.priceLists.findById(priceListId);
if (!priceList) throw new NotFoundException('Price list not found');
priceList.replaceItems(items); // the rules live in the aggregate
await this.priceLists.save(priceList);
}
}
The rules live in the aggregate
The aggregate is a normal TypeScript class with no framework imports. That is the part of DDD that matters most: the rules are in one place and can be tested without a database.
export class DomainError extends Error {}
export class PriceList {
private constructor(
readonly id: string,
private items: { materialId: string; pricePerTon: number }[],
) {}
static create(id: string) {
return new PriceList(id, []);
}
replaceItems(items: { materialId: string; pricePerTon: number }[]) {
if (items.some((item) => item.pricePerTon < 0)) {
throw new DomainError('Prices cannot be negative');
}
if (new Set(items.map((item) => item.materialId)).size !== items.length) {
throw new DomainError('Each material can appear only once');
}
this.items = items.map((item) => ({ ...item }));
}
get itemCount() {
return this.items.length;
}
}
The read side: queries that skip the domain
Queries do not need the aggregate. They read exactly the shape the screen needs, straight from the ORM. This is where most of the performance work happens, and it no longer fights with the write model.
export class GetPriceListQuery {
constructor(public readonly priceListId: string) {}
}
@QueryHandler(GetPriceListQuery)
export class GetPriceListHandler implements IQueryHandler<GetPriceListQuery> {
constructor(private readonly prisma: PrismaService) {}
execute({ priceListId }: GetPriceListQuery) {
return this.prisma.priceList.findUnique({
where: { id: priceListId },
select: {
id: true,
name: true,
items: { select: { materialId: true, pricePerTon: true } },
},
});
}
}
The controller only dispatches:
@Put(':id/items')
update(@Param('id') id: string, @Body() dto: UpdatePriceListDto) {
return this.commandBus.execute(new UpdatePriceListCommand(id, dto.items));
}
@Get(':id')
get(@Param('id') id: string) {
return this.queryBus.execute(new GetPriceListQuery(id));
}
Register CqrsModule in the module's imports and the handlers as providers, and NestJS wires the buses for you.
Folder structure
price-lists/
domain/ price-list.ts, domain-error.ts
commands/ update-price-list.command.ts, update-price-list.handler.ts
queries/ get-price-list.query.ts, get-price-list.handler.ts
infrastructure/ price-list.repository.ts
price-lists.controller.ts
price-lists.module.ts
Tests that run in milliseconds
import { describe, expect, it } from 'vitest';
describe('PriceList', () => {
it('rejects the same material twice', () => {
const list = PriceList.create('pl-1');
expect(() =>
list.replaceItems([
{ materialId: 'm1', pricePerTon: 10 },
{ materialId: 'm1', pricePerTon: 12 },
]),
).toThrow(DomainError);
});
});
Handlers get a second, thin layer of tests with an in-memory repository. Queries are covered by a few integration tests against a real database.
The ceremony I skip
- Event sourcing. Storing state as rows is fine for almost every business app.
- A separate read database. One database with good indexes covers the read side until proven otherwise.
- Sagas and domain events everywhere. I add an event when a second module actually needs to react.
- Generic base repositories and abstract handler classes. Each one saves a few lines and costs readability.
I used this exact structure on a recycling management platform built with NestJS, Prisma and React: price lists, location and postal code rules and scale configuration were command and query modules with Vitest coverage, while simple lookups stayed plain services.