From 26e68a214c2b8c7760d699494a92d4e67b0ebf7a Mon Sep 17 00:00:00 2001 From: Akkiristo Date: Fri, 16 Feb 2024 22:04:39 +0100 Subject: [PATCH] Refactor socket.on("list") to include a filter parameter --- backend/src/routes/socket.ts | 13 +++++++++---- frontend/src/components/Chat/ChatFooter.tsx | 3 ++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/backend/src/routes/socket.ts b/backend/src/routes/socket.ts index 7df1aee..1eca535 100644 --- a/backend/src/routes/socket.ts +++ b/backend/src/routes/socket.ts @@ -75,12 +75,17 @@ io.on("connection", (socket) => { } }); - socket.on("list", async () => { + socket.on("list", async (filter = "") => { try { - const rooms = await Room.find({}, "name"); - const roomNames = rooms.map((room) => room.name); + const myRoomsIds = Object.keys(roomUsers).filter(roomId => roomUsers[roomId].includes(socket.id)); + let rooms = await Room.find({ + '_id': { $in: myRoomsIds }, + 'name': new RegExp(filter, 'i') + }, 'name'); + + const roomNames = rooms.map(room => room.name); socket.emit("roomsList", roomNames); - console.log("Rooms listed: ", roomNames); + console.log("Filtered rooms listed: ", roomNames); } catch (error) { console.log("Failed to list rooms: ", error); socket.emit("error", "Failed to list rooms."); diff --git a/frontend/src/components/Chat/ChatFooter.tsx b/frontend/src/components/Chat/ChatFooter.tsx index e135eb1..2c8a8fa 100644 --- a/frontend/src/components/Chat/ChatFooter.tsx +++ b/frontend/src/components/Chat/ChatFooter.tsx @@ -120,7 +120,8 @@ function ChatFooter({ roomId }: { roomId: string }) { localStorage.setItem("name", newName); break; case "list": - socket.emit("list", args.join(" ")); + const filter = args.join(" "); + socket.emit("list", filter); break; case "create": if (args.length === 0) {