import { HostingClientBase } from '../HostingClientBase' ; import { HostingConfigBase } from '../HostingConfigBase' ; import { Application } from 'egg' ; import { ClientServiceBase } from './ClientServiceBase' ; import { RepoEventBase } from '../../../plugin/event-manager/events' ; import { EventHandlerMap } from '../../../plugin/event-manager/EventHandlerMap' ; import { getClassName } from '../../../plugin/event-manager/Helper' ; export class EventManager < TConfig extends HostingConfigBase , TRawClient > extends ClientServiceBase < TConfig , TRawClient > { private oneHandlerMap : EventHandlerMap ; private allHandlerMap : EventHandlerMap ; constructor ( app , client ) { super ( app , client , 'eventService' ) ; this . oneHandlerMap = new EventHandlerMap ( ) ; this . allHandlerMap = new EventHandlerMap ( ) ; } public async onStart ( ) { } public async onDispose ( ) { } public async onConfigLoaded ( ) { } public async syncData ( ) { } public subscribeOne < T extends RepoEventBase > ( constructor , func ) { const className = getClassName ( constructor ) ; this . oneHandlerMap . add ( className , func ) ; } public unsubscribeOne < T extends RepoEventBase > ( constructor , func ) { const className = getClassName ( constructor ) ; this . oneHandlerMap . remove ( className , func ) ; } public subscribeAll < T extends RepoEventBase > ( constructor , func ) { const className = getClassName ( constructor ) ; this . allHandlerMap . add ( className , func ) ; } public async consume < T extends RepoEventBase > ( className , type , param ) { switch ( type ) { case 'worker' : try { await this . oneHandlerMap . exec ( className , param ) ; } catch ( e ) { this . logger . error ( `Error processing handlers, className=${ className }, e=` , e ) ; } break ; case 'workers' : case 'all' : try { await this . allHandlerMap . exec ( className , param ) ; } catch ( e ) { this . logger . error ( `Error processing handlers, className=${ className }, e=` , e ) ; } break ; case 'agent' : this . logger . error ( `Worker recieve agent event. className=${ className }` ) ; break ; default : break ; } } public publish < T > ( type , constructor , param ) { this . app . event . publish ( type , constructor , param ) ; } } type EventHandler < T > = ( event : T ) => Promise < void > ;