Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 };
  }
}

like image 439
servinlp Avatar asked May 02 '19 09:05

servinlp


People also ask

What is Gateway Nestjs?

This section covers the aspects of Nest that are specific to WebSockets. In Nest, a gateway is simply a class annotated with @WebSocketGateway() decorator. Technically, gateways are platform-agnostic which makes them compatible with any WebSockets library once an adapter is created.

Is Socket.IO a library or framework?

Socket.IO is an event-driven library for real-time web applications. It enables real-time, bi-directional communication between web clients and servers. It has two parts: a client-side library that runs in the browser, and a server-side library for Node. js.


1 Answers

With the latest Nest JS update you can use this code where the room name can be sent from the front-end and it will passed on to the 'data' variable:

@SubscribeMessage('createRoom')
  createRoom(@MessageBody() data: string, @ConnectedSocket() client: Socket) {
    client.join(data, err => {
      if (err) {
        this.logger.error(err);
      }
    });
  }
like image 189
Arka Saha Avatar answered Sep 23 '22 01:09

Arka Saha