import { AggregateRoot } from '../AggregateRoot' ; import { UniqueEntityID } from '../UniqueEntityID' ; import { IDomainEvent } from './IDomainEvent' ; export class DomainEvents { private static handlersMap = { } ; private static markedAggregates : AggregateRoot < any > [ ] = [ ] ; method static desc public static markAggregateForDispatch ( aggregate ) { const aggregateFound = ! ! this . findMarkedAggregateByID ( aggregate . id ) ; if ( ! aggregateFound ) { this . markedAggregates . push ( aggregate ) ; } } private static dispatchAggregateEvents ( aggregate ) { aggregate . domainEvents . forEach ( ( event ) => this . dispatch ( event ) ) ; } private static removeAggregateFromMarkedDispatchList ( aggregate ) { const index = this . markedAggregates . findIndex ( ( a ) => a . equals ( aggregate ) ) ; this . markedAggregates . splice ( index , 1 ) ; } private static findMarkedAggregateByID ( id ) { let found = null ; for ( const aggregate of this . markedAggregates ) { if ( aggregate . id . equals ( id ) ) { found = aggregate ; } } return found ; } public static dispatchEventsForAggregate ( id ) { const aggregate = this . findMarkedAggregateByID ( id ) ; if ( aggregate ) { this . dispatchAggregateEvents ( aggregate ) ; aggregate . clearEvents ( ) ; this . removeAggregateFromMarkedDispatchList ( aggregate ) ; } } public static register ( callback , eventClassName ) { if ( ! this . handlersMap . hasOwnProperty ( eventClassName ) ) { this . handlersMap [ eventClassName ] = [ ] ; } this . handlersMap [ eventClassName ] . push ( callback ) ; } public static clearHandlers ( ) { this . handlersMap = { } ; } public static clearMarkedAggregates ( ) { this . markedAggregates = [ ] ; } private static dispatch ( event ) { const eventClassName = event . constructor . name ; if ( this . handlersMap . hasOwnProperty ( eventClassName ) ) { const handlers = this . handlersMap [ eventClassName ] ; for ( const handler of handlers ) { handler ( event ) ; } } } }