import { InferableAction } from '@ulangi/ulangi-action' ; import { Action , AnyAction , Dispatch , Middleware } from 'redux' ; import * as uuid from 'uuid' ; import { Event } from './interfaces/Event' ; import { EventListener } from './types/EventListener' ; export class EventFacade { private currentId : number = 0 ; private subscribeMap : Map < number , EventListener > = new Map ( ) ; public getMiddleware ( ) { return ( ) : ReturnType < Middleware > => { return ( next ) : Dispatch < Action > => { return < Action > ( action ) : Action => { const result = next ( action ) ; this . notifySubscribers ( { eventId : uuid . v4 ( ) , action : new InferableAction ( action . type , action . payload ) , } ) ; return ( result as unknown ) as Action ; } ; } ; } ; } public subscribe ( listener ) { const currentId = this . nextId ( ) ; this . subscribeMap . set ( currentId , listener ) ; return ( ) : void => this . unsubscribe ( currentId ) ; } private unsubscribe ( id ) { this . subscribeMap . delete ( id ) ; } private notifySubscribers ( event ) { for ( const [ id , listener ] of this . subscribeMap . entries ( ) ) { listener ( event , ( ) : void => this . unsubscribe ( id ) ) ; } } private nextId ( ) { return ++ this . currentId ; } }