Skip to content

Commit b9ce6a2

Browse files
authored
refactor: create specific adapter for parent namespaces (#4950)
1 parent 54dabe5 commit b9ce6a2

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

lib/parent-namespace.ts

+19-8
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {
66
DefaultEventsMap,
77
EventNamesWithoutAck,
88
} from "./typed-events";
9+
import { Adapter } from "socket.io-adapter";
910
import type { BroadcastOptions } from "socket.io-adapter";
1011
import debugModule from "debug";
1112

@@ -33,7 +34,7 @@ export class ParentNamespace<
3334
SocketData = any
3435
> extends Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData> {
3536
private static count: number = 0;
36-
private children: Set<
37+
private readonly children: Set<
3738
Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData>
3839
> = new Set();
3940

@@ -47,13 +48,7 @@ export class ParentNamespace<
4748
* @private
4849
*/
4950
_initAdapter(): void {
50-
const broadcast = (packet: any, opts: BroadcastOptions) => {
51-
this.children.forEach((nsp) => {
52-
nsp.adapter.broadcast(packet, opts);
53-
});
54-
};
55-
// @ts-ignore FIXME is there a way to declare an inner class in TypeScript?
56-
this.adapter = { broadcast };
51+
this.adapter = new ParentBroadcastAdapter(this, this.children);
5752
}
5853

5954
public emit<Ev extends EventNamesWithoutAck<EmitEvents>>(
@@ -112,3 +107,19 @@ export class ParentNamespace<
112107
throw new Error("fetchSockets() is not supported on parent namespaces");
113108
}
114109
}
110+
111+
/**
112+
* A dummy adapter that only supports broadcasting to child (concrete) namespaces.
113+
* @private file
114+
*/
115+
class ParentBroadcastAdapter extends Adapter {
116+
constructor(parentNsp: any, private readonly children: Set<Namespace>) {
117+
super(parentNsp);
118+
}
119+
120+
broadcast(packet: any, opts: BroadcastOptions) {
121+
this.children.forEach((nsp) => {
122+
nsp.adapter.broadcast(packet, opts);
123+
});
124+
}
125+
}

0 commit comments

Comments
 (0)