I'm trying to add parameters/settings to my socket room on top of the default room (roomid) I've tried to read up on socket.io docs and looked up online but I couldn't find much help
I initialize a new game room id and join the room with the code snippet below
let newRoom = `A ${colors[rando[0]]} ${animals[rando[1]]}`
socket.join(newRoom)
I tried:
io.sockets.adapter.rooms[newRoom].roomSetting = "foo"
I'm using socket.io v4!
CodePudding user response:
I ended up initializing my own room object where each room has settings attached to it. Spent too much time trying to figure out socket rooms but I guess things are un-documented for a reason. Lesson learned!
const rooms = {};
After initializing the rooms remove any dead/destroyed rooms,
function getActiveRooms(rooms) {
const arr = Array.from(io.sockets.adapter.rooms);
const filtered = arr.filter(room => !room[1].has(room[0]))
const res = filtered.filter(i => i[1].size === 1);
const r = res.map(r => r[0])
// loop through rooms and remove rooms that are not in r
// and store someSettings value in an array
const someSetting = [];
for (const [key, value] of Object.entries(rooms)) {
if (!r.includes(key)) {
delete rooms[key]
} else {
someSetting.push(value.someSetting)
}
}
return ([r, someSettings]);
}
Output would be something like...
["roomName", "someSetting1", "someSetting2" ...etc]