From 1f54ee08c67151303f17b5adcd1d3708df2d0fe1 Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Wed, 18 Sep 2024 12:26:22 +0200 Subject: [PATCH] refactor(sio): simplify middleware execution --- packages/socket.io/lib/namespace.ts | 12 ++++++------ packages/socket.io/lib/parent-namespace.ts | 2 +- packages/socket.io/lib/socket.ts | 9 +++++---- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/packages/socket.io/lib/namespace.ts b/packages/socket.io/lib/namespace.ts index 023b1f7f6a..27c71b22a8 100644 --- a/packages/socket.io/lib/namespace.ts +++ b/packages/socket.io/lib/namespace.ts @@ -150,8 +150,7 @@ export class Namespace< SocketData >; - /** @private */ - _fns: Array< + protected _fns: Array< ( socket: Socket, next: (err?: ExtendedError) => void, @@ -221,18 +220,19 @@ export class Namespace< */ private run( socket: Socket, - fn: (err: ExtendedError | null) => void, + fn: (err?: ExtendedError) => void, ) { + if (!this._fns) return fn(); + const fns = this._fns.slice(0); - if (!fns.length) return fn(null); function run(i: number) { - fns[i](socket, function (err) { + fns[i](socket, (err) => { // upon error, short-circuit if (err) return fn(err); // if no middleware left, summon callback - if (!fns[i + 1]) return fn(null); + if (!fns[i + 1]) return fn(); // go on to next run(i + 1); diff --git a/packages/socket.io/lib/parent-namespace.ts b/packages/socket.io/lib/parent-namespace.ts index 9df17da279..6139b8e969 100644 --- a/packages/socket.io/lib/parent-namespace.ts +++ b/packages/socket.io/lib/parent-namespace.ts @@ -67,7 +67,7 @@ export class ParentNamespace< ): Namespace { debug("creating child namespace %s", name); const namespace = new Namespace(this.server, name); - namespace._fns = this._fns.slice(0); + this._fns.forEach((fn) => namespace.use(fn)); this.listeners("connect").forEach((listener) => namespace.on("connect", listener), ); diff --git a/packages/socket.io/lib/socket.ts b/packages/socket.io/lib/socket.ts index 0adc9fea79..bc31441382 100644 --- a/packages/socket.io/lib/socket.ts +++ b/packages/socket.io/lib/socket.ts @@ -961,17 +961,18 @@ export class Socket< * @param {Function} fn - last fn call in the middleware * @private */ - private run(event: Event, fn: (err: Error | null) => void): void { + private run(event: Event, fn: (err?: Error) => void): void { + if (!this.fns.length) return fn(); + const fns = this.fns.slice(0); - if (!fns.length) return fn(null); function run(i: number) { - fns[i](event, function (err) { + fns[i](event, (err) => { // upon error, short-circuit if (err) return fn(err); // if no middleware left, summon callback - if (!fns[i + 1]) return fn(null); + if (!fns[i + 1]) return fn(); // go on to next run(i + 1);