Skip to content

Commit

Permalink
refactor(sio): simplify middleware execution
Browse files Browse the repository at this point in the history
  • Loading branch information
darrachequesne committed Sep 18, 2024
1 parent 923a12e commit 1f54ee0
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 11 deletions.
12 changes: 6 additions & 6 deletions packages/socket.io/lib/namespace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,7 @@ export class Namespace<
SocketData
>;

/** @private */
_fns: Array<
protected _fns: Array<
(
socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>,
next: (err?: ExtendedError) => void,
Expand Down Expand Up @@ -221,18 +220,19 @@ export class Namespace<
*/
private run(
socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>,
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);
Expand Down
2 changes: 1 addition & 1 deletion packages/socket.io/lib/parent-namespace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export class ParentNamespace<
): Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData> {
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),
);
Expand Down
9 changes: 5 additions & 4 deletions packages/socket.io/lib/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 1f54ee0

Please sign in to comment.