Reputation: 795
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 };
}
}
Upvotes: 18
Views: 23916
Reputation: 71
The issue I had was coming from the wrong import.
import { Socket } from 'socket.io-client' //wrong
import { Socket } from 'socket.io' //good
@SubscribeMessage('room')
joinRoom(socket: Socket, roomId: string) {
socket.join(roomId);
}
Upvotes: 1
Reputation: 795
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' };
}
Upvotes: 30
Reputation: 79
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);
}
});
}
Upvotes: 8