import { Injectable } from '@nestjs/common' ; import { Type } from '../common/shared-types' ; import { MpcastEvent } from './mpcast-event' ; export type EventHandler < T extends MpcastEvent > = ( event : T ) => void ; export type UnsubscribeFn = ( ) => void ; description docsCategory docsWeight @ Injectable ( ) export class EventBus { private subscriberMap = new Map < Type < MpcastEvent > , Array < EventHandler < any > > > ( ) ; description publish ( event ) { const eventType = ( event as any ) . constructor ; const handlers = this . subscriberMap . get ( eventType ) ; if ( handlers ) { const length = handlers . length ; for ( let i = 0 ; i < length ; i ++ ) { handlers [ i ] ( event ) ; } } } description subscribe < T extends MpcastEvent > ( type , handler ) { const handlers = this . subscriberMap . get ( type ) || [ ] ; if ( ! handlers . includes ( handler ) ) { handlers . push ( handler ) ; } this . subscriberMap . set ( type , handlers ) ; return ( ) => this . subscriberMap . set ( type , handlers . filter ( h => h !== handler ) ) ; } }