import { SubscribeMessage , WebSocketGateway } from '@nestjs/websockets' ; import { Socket } from 'socket.io' ; import { IMessage , IParticipant , IThread } from './message.interface' ; import { MessageService } from './message.service' ; @ WebSocketGateway ( ) export class MessageGateway { constructor ( private readonly messageService ) { } @ SubscribeMessage ( 'SEND_MESSAGE_SUCCESS' ) public async sendMessage ( io , data ) { const participants = await this . messageService . findOtherParticipantsInThread ( { threadId : data . thread . id , userId : ( io as any ) . token . id } ) ; await this . dispatchMessage ( 'SEND_MESSAGE_SUCCESS' , io , participants , data ) ; return data ; } @ SubscribeMessage ( 'CREATE_THREAD_SUCCESS' ) public async createThread ( io , data ) { const participants = await this . messageService . findOtherParticipantsInThread ( { threadId : data . id , userId : ( io as any ) . token . id } ) ; await this . dispatchMessage ( 'GET_THREAD_SUCCESS' , io , participants , data ) ; return data ; } private async dispatchMessage ( id , io , participants , data ) { for ( const participant of participants ) { ; ( io . server . of ( '/' ) . adapter as any ) . customRequest ( participant . userId , ( error , socketIds ) => { if ( error ) { console . log ( error ) ; } ; [ ] . concat . apply ( [ ] , socketIds ) . forEach ( x => { io . to ( x ) . emit ( id , data ) ; } ) ; } ) ; } } }