Skip to content

Commit

Permalink
fix: allow numeric rooms
Browse files Browse the repository at this point in the history
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
  • Loading branch information
darrachequesne committed Nov 15, 2021
1 parent bbfb84a commit 214b5d1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
10 changes: 9 additions & 1 deletion lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ interface Request {
[other: string]: any;
}

const isNumeric = (str) => !isNaN(str) && !isNaN(parseFloat(str));

export interface RedisAdapterOptions {
/**
* the name of the key to pub/sub events on as prefix
Expand Down Expand Up @@ -130,7 +132,7 @@ export class RedisAdapter extends Adapter {
}

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

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

private hasRoom(room): boolean {
// @ts-ignore
const hasNumericRoom = isNumeric(room) && this.rooms.has(parseFloat(room));
return hasNumericRoom || this.rooms.has(room);
}

/**
* Called on request from another node
*
Expand Down
13 changes: 12 additions & 1 deletion test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ let namespace1, namespace2, namespace3;
let client1, client2, client3;
let socket1, socket2, socket3;

const shouldNotHappen = (done) => () => done(new Error("should not happen"));

[
{
name: "socket.io-redis",
Expand Down Expand Up @@ -44,7 +46,7 @@ let socket1, socket2, socket3;
socket2.broadcast.emit("woot", [], { a: "b" }, buf, array);
});

it("broadcasts to rooms", (done) => {
it("broadcasts to a room", (done) => {
socket1.join("woot");
client2.emit("do broadcast");

Expand All @@ -66,6 +68,15 @@ let socket1, socket2, socket3;
});
});

it("broadcasts to a numeric room", (done) => {
socket1.join(123);
namespace2.to(123).emit("broadcast");

client1.on("broadcast", done);
client2.on("broadcast", shouldNotHappen(done));
client3.on("broadcast", shouldNotHappen(done));
});

it("uses a namespace to broadcast to rooms", (done) => {
socket1.join("woot");
client2.emit("do broadcast");
Expand Down

0 comments on commit 214b5d1

Please sign in to comment.