* Looks up a namespace. * * @example * // with a simple string * const myNamespace = io.of("/my-namespace"); * * // with a regex * const dynamicNsp = io.of(/^\/dynamic-\d+$/).on("connection", (socket) => { * const namespace = socket.nsp; // newNamespace.name === "/dynamic-1
(
name: string | RegExp | ParentNspNameMatchFn,
fn?: (
socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>
) => void
)
| 689 | * @param fn optional, nsp `connection` ev handler |
| 690 | */ |
| 691 | public of( |
| 692 | name: string | RegExp | ParentNspNameMatchFn, |
| 693 | fn?: ( |
| 694 | socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData> |
| 695 | ) => void |
| 696 | ): Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData> { |
| 697 | if (typeof name === "function" || name instanceof RegExp) { |
| 698 | const parentNsp = new ParentNamespace(this); |
| 699 | debug("initializing parent namespace %s", parentNsp.name); |
| 700 | if (typeof name === "function") { |
| 701 | this.parentNsps.set(name, parentNsp); |
| 702 | } else { |
| 703 | this.parentNsps.set( |
| 704 | (nsp, conn, next) => next(null, (name as RegExp).test(nsp)), |
| 705 | parentNsp |
| 706 | ); |
| 707 | this.parentNamespacesFromRegExp.set(name, parentNsp); |
| 708 | } |
| 709 | if (fn) { |
| 710 | // @ts-ignore |
| 711 | parentNsp.on("connect", fn); |
| 712 | } |
| 713 | return parentNsp; |
| 714 | } |
| 715 | |
| 716 | if (String(name)[0] !== "/") name = "/" + name; |
| 717 | |
| 718 | let nsp = this._nsps.get(name); |
| 719 | if (!nsp) { |
| 720 | for (const [regex, parentNamespace] of this.parentNamespacesFromRegExp) { |
| 721 | if (regex.test(name as string)) { |
| 722 | debug("attaching namespace %s to parent namespace %s", name, regex); |
| 723 | return parentNamespace.createChild(name as string); |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | debug("initializing namespace %s", name); |
| 728 | nsp = new Namespace(this, name); |
| 729 | this._nsps.set(name, nsp); |
| 730 | if (name !== "/") { |
| 731 | // @ts-ignore |
| 732 | this.sockets.emitReserved("new_namespace", nsp); |
| 733 | } |
| 734 | } |
| 735 | if (fn) nsp.on("connect", fn); |
| 736 | return nsp; |
| 737 | } |
| 738 | |
| 739 | /** |
| 740 | * Closes server connection |
no test coverage detected