Skip to content

Commit

Permalink
Mix except with rooms
Browse files Browse the repository at this point in the history
  • Loading branch information
sebamarynissen committed Feb 2, 2021
1 parent de5f0d3 commit 1b69524
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 14 deletions.
28 changes: 14 additions & 14 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,20 @@ export class Adapter extends EventEmitter {
packet.nsp = this.nsp.name;
const encodedPackets = this.encoder.encode(packet);

// Allow ids in `except` to be room ids.
if (except.size > 0) {
const exclude = except;
except = new Set(except);
for (const id of exclude) {
if (!this.rooms.has(id)) continue;
for (const sid of this.rooms.get(id)) {
if (sid !== id) {
except.add(sid);
}
}
}
}

if (rooms.size) {
for (const room of rooms) {
if (!this.rooms.has(room)) continue;
Expand All @@ -152,20 +166,6 @@ export class Adapter extends EventEmitter {
}
}
} else {
// Allow ids in `except` to be room ids.
if (except.size > 0) {
const exclude = except;
except = new Set(except);
for (const id of exclude) {
if (!this.rooms.has(id)) continue;
for (const sid of this.rooms.get(id)) {
if (sid !== id) {
except.add(sid);
}
}
}
}

for (const [id] of this.sids) {
if (except.has(id)) continue;
const socket = this.nsp.sockets.get(id);
Expand Down
33 changes: 33 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,39 @@ describe("socket.io-adapter", () => {
expect(ids).to.eql(["s2"]);
});

it("should exclude sockets in specific rooms when broadcasting to rooms", () => {
let ids = [];
function socket(id) {
return [
id,
{
id,
packet() {
ids.push(id);
}
}
];
}
const nsp = {
server: {
encoder: {
encode() {}
}
},
sockets: new Map([socket("s1"), socket("s2"), socket("s3")])
};
const adapter = new Adapter(nsp);
adapter.addAll("s1", new Set(["r1", "r2"]));
adapter.addAll("s2", new Set(["r2"]));
adapter.addAll("s3", new Set(["r1"]));

adapter.broadcast([], {
rooms: new Set(["r1"]),
except: new Set(["r2"])
});
expect(ids).to.eql(["s3"]);
});

describe("events", () => {
it("should emit a 'create-room' event", done => {
const adapter = new Adapter({ server: { encoder: null } });
Expand Down

0 comments on commit 1b69524

Please sign in to comment.