Skip to content

Instantly share code, notes, and snippets.

@alexbridge
Last active October 1, 2019 11:19
Show Gist options
  • Save alexbridge/2fab3f56918f3a57ff0dddbb23d13c14 to your computer and use it in GitHub Desktop.
Save alexbridge/2fab3f56918f3a57ff0dddbb23d13c14 to your computer and use it in GitHub Desktop.
Simle JS middleware implementation (ES6 Class version)
class Middleware {
use(fn) {
this.go = (prev => item => {
return prev(fn(item));
}
)(this.go)
}
go(item) {
console.count('GO');
return item;
}
}
const middleware = new Middleware();
middleware.use(item => {
console.count('USE : foo');
item.foo = 'bar';
return item;
})
middleware.use(item => {
console.count('USE : bar');
item.bar = 'foo';
return item;
})
console.warn(middleware.go({ id: 1 }))
```
USE : bar: 1
USE : foo: 1
GO: 1
{ id: 1, bar: 'foo', foo: 'bar' }
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment