Skip to content

Commit

Permalink
feat: allow excluding all sockets in a room (#66)
Browse files Browse the repository at this point in the history
  • Loading branch information
sebamarynissen committed Feb 26, 2021
1 parent c95ab42 commit 985bb41
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/index.ts
Expand Up @@ -126,18 +126,32 @@ export class Adapter extends EventEmitter {
*/
public broadcast(packet: any, opts: BroadcastOptions): void {
const rooms = opts.rooms;
const except = opts.except || new Set();
const flags = opts.flags || {};
const packetOpts = {
preEncoded: true,
volatile: flags.volatile,
compress: flags.compress
};
const ids = new Set();
let except = opts.except || new Set();

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 Down
66 changes: 66 additions & 0 deletions test/index.js
Expand Up @@ -58,6 +58,72 @@ describe("socket.io-adapter", () => {
expect(adapter.socketRooms("s4")).to.be(undefined);
});

it("should exclude sockets in specific rooms when broadcasting", () => {
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"]));
adapter.addAll("s2", new Set());
adapter.addAll("s3", new Set(["r1"]));

adapter.broadcast([], {
rooms: new Set(),
except: new Set(["r1"])
});
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 985bb41

Please sign in to comment.