import { Room , Message } from '../../models' ; import { MessageSocket } from './message' ; export class RoomSocket { nsp : any ; name : string ; data : any ; socket : any ; rooms : Room [ ] = [ ] ; messageSockets : MessageSocket [ ] = [ ] ; constructor ( private io ) { this . nsp = this . io . of ( '/room' ) ; this . nsp . on ( 'connection' , ( socket ) => { console . log ( 'Client connected' ) ; this . socket = socket ; this . updateMessageSockets ( ) ; this . listen ( ) ; } ) ; } private listen ( ) { this . socket . on ( 'disconnect' , ( ) => this . disconnect ( ) ) ; this . socket . on ( 'create' , ( name ) => this . create ( name ) ) ; this . socket . on ( 'remove' , ( name ) => this . remove ( name ) ) ; this . socket . on ( 'list' , ( ) => this . list ( ) ) ; } private disconnect ( ) { console . log ( 'Client disconnected' ) ; } private create ( name ) { Room . create ( name ) . subscribe ( room => this . list ( ) , error => console . error ( 'Room creation failed' , error ) ) ; } private remove ( name ) { Room . find ( name ) . subscribe ( room => room . remove ( ) . subscribe ( x => { } , e => { } , ( ) => this . list ( ) ) , error => console . error ( 'Room removal failed' , error ) ) ; } private list ( ) { Room . list ( ) . subscribe ( rooms => { this . rooms = rooms ; this . updateMessageSockets ( ) ; this . nsp . emit ( 'item' , rooms ) ; } ) ; } private updateMessageSockets ( ) { let validRooms = { } ; for ( const room of this . rooms ) { validRooms [ room . name ] = true ; const matches = this . messageSockets . filter ( messageSocket => messageSocket . room . name === room . name ) ; if ( matches . length == 0 ) { console . log ( 'creating new namespace for' , room . name ) ; this . messageSockets . push ( new MessageSocket ( this . io , room ) ) ; } } for ( const index in this . messageSockets ) { const messageSocket = this . messageSockets [ index ] ; if ( ! validRooms [ messageSocket . room . name ] ) { this . messageSockets . splice ( parseInt ( index , 10 ) , 1 ) ; } } } }