Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions lib/parent-namespace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
DefaultEventsMap,
EventNamesWithoutAck,
} from "./typed-events";
import { Adapter } from "socket.io-adapter";
import type { BroadcastOptions } from "socket.io-adapter";
import debugModule from "debug";

Expand Down Expand Up @@ -33,7 +34,7 @@ export class ParentNamespace<
SocketData = any
> extends Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData> {
private static count: number = 0;
private children: Set<
private readonly children: Set<
Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData>
> = new Set();

Expand All @@ -47,13 +48,7 @@ export class ParentNamespace<
* @private
*/
_initAdapter(): void {
const broadcast = (packet: any, opts: BroadcastOptions) => {
this.children.forEach((nsp) => {
nsp.adapter.broadcast(packet, opts);
});
};
// @ts-ignore FIXME is there a way to declare an inner class in TypeScript?
this.adapter = { broadcast };
this.adapter = new ParentBroadcastAdapter(this, this.children);
}

public emit<Ev extends EventNamesWithoutAck<EmitEvents>>(
Expand Down Expand Up @@ -112,3 +107,19 @@ export class ParentNamespace<
throw new Error("fetchSockets() is not supported on parent namespaces");
}
}

/**
* A dummy adapter that only supports broadcasting to child (concrete) namespaces.
* @private file
*/
class ParentBroadcastAdapter extends Adapter {
constructor(parentNsp: any, private readonly children: Set<Namespace>) {
super(parentNsp);
}

broadcast(packet: any, opts: BroadcastOptions) {
this.children.forEach((nsp) => {
nsp.adapter.broadcast(packet, opts);
});
}
}