Created
April 3, 2018 15:13
-
-
Save nicholasrq/cc631ed7948766794c3823cd26329a7c to your computer and use it in GitHub Desktop.
JS Middleware class in 8 lines
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{ | |
constructor(){ this.m = [] } | |
use(fn){ this.m.push(fn) } | |
run(d, f){ this._execute(d, f) } | |
_execute(d, f){ this.m.reduceRight((n, c) => v => c(v, n), f)(d) } | |
} | |
// usage | |
const m = new Middleware(); | |
// append middlewares | |
m.use(function(data, next){ | |
next(data + 1) | |
}) | |
m.use(function(data, next){ | |
next(data + 1) | |
}) | |
m.use(function(data, next){ | |
next(data + 1) | |
}) | |
// execute | |
// first argument – data | |
// second argument – finish function, will | |
// recieve result after all middlewares | |
m.run(1, function(result){ | |
console.log(result) //=> 4 | |
}) | |
// to iterrupt middlewares chain just don't call next() | |
// you can test it out by playing with this code above |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment