advanced

NestJS CQRS module

Понимайте commands, queries, handlers, events, sagas, transactional boundaries и когда CQRS добавляет больше ceremony, чем value.

Пакет `@nestjs/cqrs` разделяет writes (commands) и reads (queries). Commands меняют state через handlers; queries возвращают data без side effects. Events отвязывают реакции от write path.

					@CommandHandler(CreateOrderCommand)
export class CreateOrderHandler implements ICommandHandler<CreateOrderCommand> {
  constructor(private readonly repo: OrdersRepository) {}
  async execute(command: CreateOrderCommand) {
    const order = Order.create(command.payload);
    await this.repo.save(order);
    return order.id;
  }
}
				

`CommandBus`, `QueryBus` и `EventBus` диспатчат messages в handlers. Sagas оркестрируют multi-step workflows по events. CQRS уместен, когда read и write models расходятся или event-driven реакций много.

На интервью: когда CQRS даёт value vs ceremony, transactional boundaries на handler, eventual consistency на read side.

Типовые ошибки: CQRS для простого CRUD, цепочки handlers без границ, events без idempotency.

Компромисс — между простотой, производительностью, безопасностью и эксплуатацией: назовите, что оптимизировали и какую цену приняли.

Чеклист:

  • Commands для writes, queries для reads.
  • Один handler на тип message.
  • Domain events после успешных commits.
  • CQRS только при оправданной сложности модели.