Last active
April 11, 2024 08:17
-
-
Save paulborm/4246a0d826422a52c6d37e0678909263 to your computer and use it in GitHub Desktop.
Simple middleware implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @template Context | |
* @callback Handler | |
* @param {Context} context | |
* @param {function(): void} next | |
*/ | |
/** | |
* @template Context | |
* @example | |
* const middleware = new Middleware([firstHandler, secondHandler]); | |
* middleware.handle(someObject) | |
*/ | |
class Middleware { | |
/** | |
* @param {Handler<Context>[]} handlers | |
*/ | |
constructor(handlers) { | |
this.handlers = handlers; | |
} | |
/** @param {Context} context */ | |
handle(context) { | |
let index = 0; | |
const next = () => { | |
if (index >= this.handlers.length) { | |
return; | |
} | |
index++; | |
this.handlers[index](context, next); | |
} | |
next(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example