import { Logger , UseFilters } from '@nestjs/common' ; import { OnGatewayConnection , OnGatewayDisconnect , OnGatewayInit , SubscribeMessage , WebSocketGateway , WebSocketServer } from '@nestjs/websockets' ; import { WebsocketsExceptionFilter } from 'nestjs-extensions' ; import * as redis from 'redis' ; import * as socketIoRedis from 'socket.io-redis' ; const { REDIS_HOST , REDIS_PORT , REDIS_AUTH_PASS } = process . env as any ; @ WebSocketGateway ( ) @ UseFilters ( new WebsocketsExceptionFilter ( ) ) export class ApplicationGateway implements OnGatewayInit , OnGatewayConnection , OnGatewayDisconnect { private logger = new Logger ( 'AppGateway' ) ; @ WebSocketServer ( ) public readonly io : SocketIO . Server ; async afterInit ( io ) { const options = { host : REDIS_HOST , port : REDIS_PORT , auth_pass : REDIS_AUTH_PASS } ; const pubClient = redis . createClient ( options ) ; const subClient = redis . createClient ( options ) ; io . adapter ( socketIoRedis ( { pubClient , subClient } ) ) ; } async handleConnection ( socket ) { this . logger . log ( `Socket ID: ${ socket . id } connected!` ) ; } async handleDisconnect ( socket ) { this . logger . log ( `Socket ID: ${ socket . id } disconnected!` ) ; } @ SubscribeMessage ( 'WELCOME' ) async onWelcome ( socket , data ) { this . io . emit ( 'WELCOME' , `Welcome ${ socket . id }.` ) ; } }