Skip to content

Commit 214b5d1

Browse files
fix: allow numeric rooms
The support for numeric rooms was lost when we used a Map for the 'rooms' property, which stores the relationships between Socket IDs and rooms ([1]). This commit restores the ability to use numbers as rooms: ```js socket.join(42); io.to(42).emit("hello"); ``` Note: for proper TypeScript support, we should also update the type of Room to `string | number` [1]: socketio/socket.io-adapter@53ed3f4 Related: #418
1 parent bbfb84a commit 214b5d1

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

lib/index.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ interface Request {
2929
[other: string]: any;
3030
}
3131

32+
const isNumeric = (str) => !isNaN(str) && !isNaN(parseFloat(str));
33+
3234
export interface RedisAdapterOptions {
3335
/**
3436
* the name of the key to pub/sub events on as prefix
@@ -130,7 +132,7 @@ export class RedisAdapter extends Adapter {
130132
}
131133

132134
const room = channel.slice(this.channel.length, -1);
133-
if (room !== "" && !this.rooms.has(room)) {
135+
if (room !== "" && !this.hasRoom(room)) {
134136
return debug("ignore unknown room %s", room);
135137
}
136138

@@ -152,6 +154,12 @@ export class RedisAdapter extends Adapter {
152154
super.broadcast(packet, opts);
153155
}
154156

157+
private hasRoom(room): boolean {
158+
// @ts-ignore
159+
const hasNumericRoom = isNumeric(room) && this.rooms.has(parseFloat(room));
160+
return hasNumericRoom || this.rooms.has(room);
161+
}
162+
155163
/**
156164
* Called on request from another node
157165
*

test/index.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ let namespace1, namespace2, namespace3;
1414
let client1, client2, client3;
1515
let socket1, socket2, socket3;
1616

17+
const shouldNotHappen = (done) => () => done(new Error("should not happen"));
18+
1719
[
1820
{
1921
name: "socket.io-redis",
@@ -44,7 +46,7 @@ let socket1, socket2, socket3;
4446
socket2.broadcast.emit("woot", [], { a: "b" }, buf, array);
4547
});
4648

47-
it("broadcasts to rooms", (done) => {
49+
it("broadcasts to a room", (done) => {
4850
socket1.join("woot");
4951
client2.emit("do broadcast");
5052

@@ -66,6 +68,15 @@ let socket1, socket2, socket3;
6668
});
6769
});
6870

71+
it("broadcasts to a numeric room", (done) => {
72+
socket1.join(123);
73+
namespace2.to(123).emit("broadcast");
74+
75+
client1.on("broadcast", done);
76+
client2.on("broadcast", shouldNotHappen(done));
77+
client3.on("broadcast", shouldNotHappen(done));
78+
});
79+
6980
it("uses a namespace to broadcast to rooms", (done) => {
7081
socket1.join("woot");
7182
client2.emit("do broadcast");

0 commit comments

Comments
 (0)