Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Created January 22, 2019 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/b4589b853a0c2544af287e70ce76d080 to your computer and use it in GitHub Desktop.
Save ccnokes/b4589b853a0c2544af287e70ce76d080 to your computer and use it in GitHub Desktop.
Really basic express-like middleware implementation
class Middleware {
private middlewares = [];
push(...middlewares) {
this.middlewares.push.apply(this.middlewares, middlewares);
}
run(...args) {
let i = 0;
const next = () => {
if (i < this.middlewares.length) {
this.middlewares[i++].apply(null, [...args, next]);
}
}
next();
}
}
// test it out
let m = new Middleware();
m.push(
(ctx, next) => {
console.log(ctx);
ctx.a = 1;
next();
},
(ctx, next) => {
console.log(ctx);
ctx.a = 2;
next()
}
);
m.run({ a: 0 })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment