Provide a NestJS boilerplate with event sourcing using EventStoreDB. The write side appends events while a separate projection process reads the event stream and updates a MongoDB read view model.
Assistant
Outlining NestJS event sourcing boilerplate
The plan details a monorepo with two NestJS apps: a write service handling commands and appending events to EventStoreDB, and a projection service subscribing to the event stream and updating MongoDB. It covers key modules, event definitions, CQRS command handlers, EventStoreDB client setup, projection subscription, concurrency management, and essential environment variables. Next step is producing minimal example code for both apps and shared libs reflecting this architecture.
Below is a minimal, end‑to‑end NestJS boilerplate that uses EventStoreDB for the write side and a separate projection process that reads the event stream and updates a MongoDB read model. It is organized as two apps inside a monorepo:
npm i @nestjs/common @nestjs/core @nestjs/cqrs @nestjs/mongoose mongoose @eventstore/db-client
npm i -D @types/node typescript ts-node
Write Service (Event Production)
apps/write/src/eventstore.module.ts
ts
import { Module } from '@nestjs/common';
import { EventStoreDBClient } from '@eventstore/db-client';
export const EVENTSTOREDB = 'EVENTSTOREDB';
@Module({
providers: [
{
provide: EVENTSTOREDB,
useFactory: async () => {
// Adjust connection string for your environment
return EventStoreDBClient.connectionString`esdb://localhost:2113?tls=false`;
},
},
],
exports: [EVENTSTOREDB],
})
export class EventStoreModule {}
apps/write/src/events/user-created.event.ts
ts
export class UserCreatedEvent {
constructor(
public readonly userId: string,
public readonly email: string,
public readonly name: string,
) {}
// A simple "type" field for downstream projection
static readonly type = 'UserCreated';
}
import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { EventStoreDBClient, START, jsonEvent, ResolvedEvent } from '@eventstore/db-client';
import { UserReadModel } from './schemas/user.read.schema';
import { EVENTSTOREDB } from './eventstore.module';
@Injectable()
export class ProjectionService implements OnModuleInit {
private readonly logger = new Logger(ProjectionService.name);
constructor(
@Inject(EVENTSTOREDB) private readonly esdb: EventStoreDBClient,
@InjectModel('UserRead') private readonly userReadModel: Model<UserReadModel>,
) {}
async onModuleInit() {
this.logger.log('Starting projection subscription...');
// Here we subscribe to all events. In production, use persistent subs or specific streams.
const subscription = this.esdb.subscribeToAll({
fromPosition: START, // Could be a checkpoint persisted somewhere
});
for await (const resolved of subscription) {
await this.handleEvent(resolved);
}
}
private async handleEvent(event: ResolvedEvent) {
if (!event.event) return;
const { type, data } = event.event;
switch (type) {
case 'UserCreated': {
await this.userReadModel.updateOne(
{ _id: data.userId },
{
_id: data.userId,
email: data.email,
name: data.name,
},
{ upsert: true },
);
this.logger.log(`Projected UserCreated for ${data.userId}`);
break;
}
// Add more event types here...
default:
break;
}
}
}
apps/projection/src/projection.module.ts
ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ProjectionService } from './projection.service';
import { EventStoreModule } from './eventstore.module';
import { UserReadSchema } from './schemas/user.read.schema';
@Module({
imports: [
EventStoreModule,
// Adjust Mongo URL
MongooseModule.forRoot('mongodb://localhost:27017/my_read_model'),
MongooseModule.forFeature([{ name: 'UserRead', schema: UserReadSchema }]),
],
providers: [ProjectionService],
})
export class ProjectionModule {}
apps/projection/src/main.ts
ts
import { NestFactory } from '@nestjs/core';
import { ProjectionModule } from './projection.module';
async function bootstrap() {
const app = await NestFactory.create(ProjectionModule);
// Projection runs as a background process; no HTTP listeners needed
await app.init();
console.log('Projection service started (listening to EventStoreDB)');
}
bootstrap();
Running
Spin up EventStoreDB (e.g., docker run -it --rm -p 2113:2113 -p 1113:1113 eventstore/eventstore:latest --insecure --run-projections=None).
Start MongoDB (e.g., docker run -d -p 27017:27017 mongo).
The projection service will consume the UserCreated event and upsert the read model in Mongo.
Notes & Extensions
Checkpoints: In a real app, persist the last processed position in Mongo or Redis so projections can resume from where they left off. Replace fromPosition: START with that checkpoint.
Event Versioning: Use consistent event type naming/versioning (UserCreated_v1, etc.).
Idempotency: Ensure updates are idempotent. Mongo upserts help; you can also store event IDs to avoid reprocessing.
Persistent Subscriptions: For large systems, consider EventStoreDB persistent subscriptions instead of subscribeToAll.
CQRS: The write side can include more commands and aggregates with optimistic concurrency (expectedRevision on appendToStream).
This skeleton gives you a minimal NestJS setup demonstrating EventStoreDB on the write side and a separate projection process updating a MongoDB read view. Adjust configuration and structure to fit your production needs.