nestjs-typed-events
v1.0.2
Published
Typesafe NestJS event emitter module
Downloads
34
Maintainers
Readme
Type Safe, contract-driven event emitter module for a NestJS application.
Uses zod object defintions to create typesafe event listeners and emitter, with automatic validation of args.
Features
- End-to-end type safe wrapper for
eventemitter2
- Wild card events
- Enforce events have a listener via
contract.required(<event>, <schema>)
- Optional event listeners via
contract.optional(<event>, <schema>)
Installation
npm i eventemitter2 nestjs-typed-events
Limitations
- You can have multiple event listeners on one class only if the events have the same args signature.
Example
- Register in
app.module
import { EventContractBuilder, EventEmitterModule } from 'nestjs-typed-events';
const contract = EventContractBuilder.create()
.required(
'test.event',
z.object({
foo: z.string(),
}),
)
.optional('optional.event', z.string())
.build();
@Module({
imports: [
EventEmitterModule.forRoot(EventEmitterModule, {
contract,
}),
],
})
export class AppModule {}
- Register your event listener
import { Injectable } from '@nestjs/common';
import {
EventListenerDecoratorFactory,
ContractEvent,
} from 'nestjs-typed-events';
const ContractEvent = EventListenerDecoratorFactory(contract);
@Injectable()
@ContractEvent('test.event')
export class TestWatcher {
async handle(args: ContractEvent<typeof contract['test.event']>) {}
}
- Profit