Property 'connected' does not exist on type 'Namespace<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any>'

156 Views Asked by At

When I try to run the following code:

const endMeeting = async (meeting_id: string, socket: Socket, meeting_server: Server, payload: any) => {
    const { user_id } = payload.data;
    broadcastUsers(meeting_id, socket, meeting_server, {
        type: MeetingPayloadEnum.MEETING_ENDED,
        data: { user_id }
    });

    let users: IUser[] = await Meetings.getAllMeetingUsers(toBinaryUUID(meeting_id));
    for (let i = 0; i < users.length; i++) {
        let user = users[i];
        meeting_server.sockets.connected[user.socket_id].disconnect;
    }
}

It gives me this error message at the last line of the code:

Property 'connected' does not exist on type 'Namespace<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any>'.

It seems the code is a little bit outdated and the socket.io works another way now, but I am not sure how? How should I update this code?

1

There are 1 best solutions below

0
Aman Jakhar On BEST ANSWER

The connected property is no longer available on the sockets property of the Namespace object in the latest version of Socket.IO. Instead, you can use the sockets.sockets property to get a map of all connected sockets, and then use the get method to retrieve a specific socket by its ID. Try this code:

const endMeeting = async (meeting_id: string, socket: Socket, meeting_server: 
Server, payload: any) => {
  const { user_id } = payload.data;
  broadcastUsers(meeting_id, socket, meeting_server, {
    type: MeetingPayloadEnum.MEETING_ENDED,
    data: { user_id }
  });

  let users: IUser[] = await 
  Meetings.getAllMeetingUsers(toBinaryUUID(meeting_id));
  for (let i = 0; i < users.length; i++) {
    let user = users[i];
    meeting_server.sockets.sockets.get(user.socket_id)?.disconnect();
  }
}

You can use the optional chaining operator (?.) to handle cases where the socket with the specified ID does not exist in the map (for example, if the user has already disconnected).