Skip to content

Instantly share code, notes, and snippets.

@skrajewski
Created March 18, 2021 10:33
Show Gist options
  • Save skrajewski/7d2ad85e93921aecd6afd241677b7115 to your computer and use it in GitHub Desktop.
Save skrajewski/7d2ad85e93921aecd6afd241677b7115 to your computer and use it in GitHub Desktop.

Revisions

  1. skrajewski created this gist Mar 18, 2021.
    27 changes: 27 additions & 0 deletions pipe.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    const pipe = async (stack, context) => {
    const execute = (context) => {
    let prevIndex = -1;

    const runner = async (innerContext, index) => {
    if (index == prevIndex) {
    throw new Error('next() called more than once');
    }

    prevIndex = index;

    const middleware = stack[index];

    if (middleware) {
    return await middleware(innerContext, (ctx) => runner(ctx, index + 1));
    }
    }

    return runner(context, 0);
    };

    return execute(context);
    };

    const createPipe = (stack) => (context) => pipe(stack, context);

    module.exports = { pipe, createPipe };