Ad

How To Create Rooms With Nestjs And Socket.io

I'm trying to create a room on my nestjs backend but can't find any information on this subject. You can find the docs here. The docs don't seem to have anything on this subject.

import {
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  WsResponse,
} from '@nestjs/websockets';
import { Client, Server } from 'socket.io';

@WebSocketGateway({namespace: 'story'})
export class StoryEventsGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('createRoom')
  createRoom(client: Client, data: string): WsResponse<unknown> {
    return { event: 'roomCreated', data };
  }
}

Ad

Answer

By changing client: Client to socket: Socket you're able to use the socket object you are used to when using socket.io.

Here is the edited function.

import { Socket } from 'socket.io';
import { WsResponse } from '@nestjs/websockets';

createRoom(socket: Socket, data: string): WsResponse<unknown> {
  socket.join('aRoom');
  socket.to('aRoom').emit('roomCreated', {room: 'aRoom'});
  return { event: 'roomCreated', room: 'aRoom' };
}
Ad
source: stackoverflow.com
Ad