import { IPCManager , ICache , IRoomObject , logger } from "../internal" ; export type RoomUpdateSubscriber = ( roomId : string , data : IRoomObject | null ) => void ; const log = logger ( "room/inspector" , 36 ) ; export class RoomInspector { public subscribers : { [ name ] : Map < string , RoomUpdateSubscriber > ; } = { } ; constructor ( public ipcm , public cache ) { const _set = cache . set . bind ( cache ) ; cache . set = async ( roomId , data ) : Promise < void > => { await _set ( roomId , data ) ; log . debug ( `>> Process ${ this . ipcm . processId }: Publish "${ roomId }" for channel room_update:${ data . name }` ) ; ipcm . publish ( `room_update:${ data . name }` , roomId ) ; } ; const _remove = cache . remove . bind ( cache ) ; cache . remove = async ( roomId ) : Promise < void > => { const data = await cache . get ( roomId ) ; await _remove ( roomId ) ; if ( data ) { log . debug ( `>> Process ${ this . ipcm . processId }: Publish "${ roomId }" for channel room_update:${ data . name }` ) ; ipcm . publish ( `room_update:${ data . name }` , roomId ) ; } } ; } public async onRoomUpdate ( name , roomId ) { console . log ( `>> Process ${ this . ipcm . processId }: Room ${ name } update: ${ roomId }` ) ; const data = await this . cache . get ( roomId ) ; if ( this . subscribers [ name ] ) { this . subscribers [ name ] . forEach ( ( subscriber ) => subscriber ( roomId , data ) ) ; } } public subscribe ( id , names , subscriber ) { names . forEach ( ( name ) => { if ( ! this . subscribers [ name ] ) { this . subscribers [ name ] = new Map ( ) ; log . debug ( `>> Process ${ this . ipcm . processId }: Subscribe for room_update:${ name }` ) ; this . ipcm . subscribe < string > ( `room_update:${ name }` , ( roomId ) => this . onRoomUpdate ( name , roomId ) ) ; } this . subscribers [ name ] . set ( id , subscriber ) ; } ) ; } public unsubscribe ( id , names ) { names . forEach ( ( name ) => { this . subscribers [ name ] . delete ( id ) ; if ( ! this . subscribers [ name ] . size ) { delete this . subscribers [ name ] ; log . debug ( `>> Process ${ this . ipcm . processId }: Unsubscribe from room_update:${ name }` ) ; this . ipcm . unsubscribe ( `room_update:${ name }` ) ; } } ) ; } }