1.0.2 • Published 1 year ago

nestjs-typed-events v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

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

  1. 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 {}
  1. 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']>) {}
}
  1. Profit