Created
January 22, 2019 21:07
-
-
Save ccnokes/b4589b853a0c2544af287e70ce76d080 to your computer and use it in GitHub Desktop.
Really basic express-like 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
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