import { OnGatewayConnection , WebSocketGateway , WebSocketServer } from '@nestjs/websockets' ; import { Server , Socket } from 'socket.io' ; import { JwtService } from '@nestjs/jwt' ; import { ISubscriberJwt } from '@notifire/shared' ; @ WebSocketGateway ( ) export class WSGateway implements OnGatewayConnection { constructor ( private jwtService ) { } @ WebSocketServer ( ) server : Server ; async handleConnection ( connection ) { const { token } = connection . handshake . query ; if ( ! token || token === 'null' ) { return this . disconnect ( connection ) ; } let subscriber ; try { subscriber = await this . jwtService . verify ( token as string ) ; if ( subscriber . aud !== 'widget_user' ) { return this . disconnect ( connection ) ; } } catch ( e ) { return this . disconnect ( connection ) ; } return await connection . join ( subscriber . _id ) ; } async sendMessage ( userId , event , data ) { this . server . to ( userId ) . emit ( event , data ) ; } private disconnect ( socket ) { socket . disconnect ( ) ; } }