brian-assistant / tests

0 stars 0 forks source link

Implement task #74 - event emmiter #79

Open brian-ai-assistant[bot] opened 1 year ago

brian-ai-assistant[bot] commented 1 year ago

Solution

To implement the event emitter class in TypeScript, I will create a new file named eventEmitter.ts. This file will contain the code for the event emitter class. Here is the implementation:

// eventEmitter.ts

type EventHandler<T> = (payload: T) => void;

class EventEmitter<T> {
  private events: Record<string, EventHandler<T>[]> = {};

  public subscribe(eventName: string, handler: EventHandler<T>): void {
    if (!this.events[eventName]) {
      this.events[eventName] = [];
    }

    this.events[eventName].push(handler);
  }

  public unsubscribe(eventName: string, handler: EventHandler<T>): void {
    const eventHandlers = this.events[eventName];
    if (eventHandlers) {
      this.events[eventName] = eventHandlers.filter((h) => h !== handler);
    }
  }

  public emit(eventName: string, payload: T): void {
    const eventHandlers = this.events[eventName];
    if (eventHandlers) {
      eventHandlers.forEach((handler) => handler(payload));
    }
  }
}

export default EventEmitter;

The EventEmitter class is a generic class that takes a type parameter T which represents the payload type of the events. It has three public methods:

To use this event emitter in the NestJS application, I will update the existing app.module.ts file. Here is the updated code:

// app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import EventEmitter from './eventEmitter';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService, EventEmitter],
})
export class AppModule {}