1

I'm creating a simple chat app with rooms and I meet the problem, that, seems like socket.io can not join the room, I have schemas in mongodb, those are users, messages and rooms, for room id I provide the id of rooms schema and then want to join it with one event for example, I'm logging in from react app, then by user id I'm finding all rooms that contains my id and then want to join them all. For the second step I want to send message and I'm targeting the room that I want send the message, with .to(roomId).emit(..., ...)

but all of this tries are useless, it not works

here is the nestjs gateway code:

import { Logger } from '@nestjs/common';
import {
  WebSocketGateway,
  WebSocketServer,
  SubscribeMessage,
  OnGatewayDisconnect,
  OnGatewayInit,
  OnGatewayConnection,
  MessageBody,
  ConnectedSocket,
  WsResponse,
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';
import { UserService } from 'src/user/user.service';
import { ChatService } from './chat.service';
import { CreateChatDto } from './dto/create-chat.dto';
import { UpdateChatDto } from './dto/update-chat.dto';

@WebSocketGateway({
  cors: {
    origin: '*',
  },
})
export class ChatGateway
  implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit
{
  constructor(
    private readonly chatService: ChatService,
    private userService: UserService,
  ) {}

  private readonly logger: Logger = new Logger(ChatGateway.name);
  @WebSocketServer() server: Server;

  afterInit(client: Socket) {
    this.logger.log('Initialized SocketGateway');
  }

  handleConnection(client: Socket) {
    this.logger.log(`[connection] from client (${client.id})`);
  }

  handleDisconnect(client: Socket) {
    this.logger.log(`[disconnection] from client(${client.id})`);
  }


  //this works when user logs is
  @SubscribeMessage('setup')
  async handleJoinRoom(client: Socket, @MessageBody() userData) {
    
    //here I'm getting all rooms that contains my user id
    const rooms = await this.userService.findAll(userData);
    await this.logger.log(
      `[joinWhiteboard] ${userData}(${client.id}) joins ${userData}`,
    );

    
    await rooms.map((item) => {
      client.join(item._id.toString());
      //joining all rooms that I'm in
      client.to(item._id.toString()).emit('joined');
    });
  }

  @SubscribeMessage('new message')
  create(client: Socket, @MessageBody() recievedMessage) {
    this.logger.log(
      `[sent a new message] from (${client.id}) to ${recievedMessage.chatRoomId}`,
    );
    //sending message to the room
    client
      .to(recievedMessage.chatRoomId)
      .emit('message recieved', recievedMessage);
  }
}

in my github is the full code(react part also), please feel free if you need to see it https://github.com/Code0Breaker/chat

Vahan
  • 28
  • 3
  • 11
  • Could you describe exactly what the issue is that you're seeing? Is it simply not connecting? Erroring on connection? Or are messages not getting through? – Tevon Strand-Brown Sep 13 '22 at 17:43
  • I haven't been able to run your code, but it looks like you may have an issue in the userService.findAll method, which takes userData and finds users where $in. can you check that there are actual rooms being returned by that call? – Tevon Strand-Brown Sep 13 '22 at 17:52

0 Answers0