Skip to content

Commit

Permalink
refactor: create specific adapter for parent namespaces (#4950)
Browse files Browse the repository at this point in the history
  • Loading branch information
jokester authored Feb 19, 2024
1 parent 54dabe5 commit b9ce6a2
Showing 1 changed file with 19 additions and 8 deletions.
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);
});
}
}

0 comments on commit b9ce6a2

Please sign in to comment.