Skip to content

Instantly share code, notes, and snippets.

@nicholasrq
Created April 3, 2018 15:13
Show Gist options
  • Save nicholasrq/cc631ed7948766794c3823cd26329a7c to your computer and use it in GitHub Desktop.
Save nicholasrq/cc631ed7948766794c3823cd26329a7c to your computer and use it in GitHub Desktop.
JS Middleware class in 8 lines
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