Skip to content

Instantly share code, notes, and snippets.

@paulborm
Last active April 11, 2024 08:17
Show Gist options
  • Save paulborm/4246a0d826422a52c6d37e0678909263 to your computer and use it in GitHub Desktop.
Save paulborm/4246a0d826422a52c6d37e0678909263 to your computer and use it in GitHub Desktop.
Simple middleware implementation
/**
* @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();
}
}
@paulborm
Copy link
Author

Example

const middleware = new Middleware([firstHandler, secondHandler]);
const string = "hello world";
middleware.handle(string)

/** @type {Handler<string>} */
function firstHandler(context, next) {
	next();
}
/** @type {Handler<string>} */
function secondHandler(context, next) {
	next();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment