How to Add The Inbox Pattern To a NestJS Microservice
1. Enable the modules in AppModule
./src/AppModule.ts
import { NestMicroserviceInboxModule } from '@tsm/nest/microservice-inbox';
@Module({})
export class AppModule extends BaseAppModule {
public static imports(config: FrameworkModuleOptions<AppConfig>): (Type<object> | DynamicModule)[] {
return [
// infra
// ...
NestMicroserviceInboxModule,
];
}
// ...
}
2. Include the Inbox Pattern Entities in the TypeORM Config
In order for typeorm to recognize the entities, you need to include the glob path to the inbox entities in the entities
array in the DataSourceOptions
file.
./src/infrastructure/TypeOrm/DataSourceOptions.ts
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
export const options: Partial<PostgresConnectionOptions> = {
// ...
entities: [
// ...
`${__dirname}/../../../../../libs/nest/microservice-inbox/**/!(*.spec).{ts,js}`,
],
};
3. Add the Inbox Interceptor to the Microservice Module
Import the NestMicroserviceInboxModule
with any module that needs to use the inbox pattern.
./src/infrastructure/EventStream/EventStreamModule.ts
import { Module } from '@nestjs/common';
import { NestMicroserviceInboxModule } from '@tsm/nest/microservice-inbox';
import { MessageController } from './MessageController';
@Module({
controllers: [MessageController],
imports: [NestMicroserviceInboxModule],
})
export class EventStreamModule {}
4. Add the Interceptors to the Module's Message Controllers
Within the module that has imported NestMicroserviceInboxModule
, add the InboxInterceptor
to the message controllers using the @UseInterceptors
decorator.
./src/infrastructure/EventStream/MessageController.ts
import { Controller, UseInterceptors } from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';
import { InboxInterceptor } from '@tsm/nest/microservice-inbox';
@Controller()
export class MessageController {
@EventPattern(`DomainEvent.PatternOne`)
@UseInterceptors(InboxInterceptor)
public async handle(@Payload() event: PatternOne): Promise<void> {
// ...
}
@EventPattern(`DomainEvent.PatternTwo`)
@UseInterceptors(InboxInterceptor)
public async handleAnother(@Payload() event: PatternTwo): Promise<void> {
// ...
}
}