import { Socket , socketio } from '@loopback/socketio' ; import debugFactory from 'debug' ; const debug = debugFactory ( 'loopback:socketio:controller' ) ; socketio @ socketio ( '/' ) export class SocketIoController { constructor ( @ socketio . socket ( ) private socket ) { } param socket @ socketio . connect ( ) connect ( socket ) { debug ( 'Client connected: %s' , this . socket . id ) ; return socket . join ( 'room 1' ) ; } param msg @ socketio . subscribe ( 'subscribe-to-channel' ) async registerChannel ( msg ) { debug ( 'Subscribe to channel: %s' , msg ) ; if ( Array . isArray ( msg ) && msg . length > 0 ) { for ( const item of msg ) await this . socket . join ( item ) ; } else { throw new Error ( 'Channels data not appropriate' ) ; } } param msg @ socketio . subscribe ( 'general-message-forward' ) handleChatMessage ( msg ) { debug ( 'General forwarded message: %s' , msg ) ; this . socket . nsp . emit ( 'general-message-forward' , msg ) ; } param msg @ socketio . subscribe ( 'general-message' ) handleGeneralMessage ( msg ) { debug ( 'General Message : %s' , msg ) ; const parsedMsg = JSON . parse ( msg ) ; if ( parsedMsg ?. receiver ?. to ?. length > 0 ) { parsedMsg . receiver . to . forEach ( item => this . socket . nsp . to ( item . id ) . emit ( 'message' , { subject : parsedMsg . subject , body : parsedMsg . body , options : parsedMsg . options , } ) ) ; } else { throw new Error ( 'Inappropriate message data' ) ; } } /**
     * Register a handler for all events
     */ @ socketio . subscribe ( /.+/ ) logMessage ( ... args ) { debug ( 'Message: %s' , args ) ; } param socket @ socketio . disconnect ( ) disconnect ( ) { debug ( 'Client disconnected: %s' , this . socket . id ) ; } }