Skip to content

Instantly share code, notes, and snippets.

@riyaz-ali
Forked from darrenscerri/Middleware.js
Last active February 13, 2018 17:51
Show Gist options
  • Save riyaz-ali/e79919455180a65b2b6d673b9e850a65 to your computer and use it in GitHub Desktop.
Save riyaz-ali/e79919455180a65b2b6d673b9e850a65 to your computer and use it in GitHub Desktop.
A very minimal Javascript (ES5) Middleware Pattern Implementation
let Middleware = function() { };
// executes the middlewares supplying initial args to the first middleware
// this function returns a Promise which gets resolved after the last middleware is executed
Middleware.prototype.exec = function() {
let args = Array.prototype.slice.call(arguments);
let that = this
return new Promise(function(resolve /*,reject */){
let pr = this;
let end = function(){
let a = Array.prototype.slice.call(arguments);
resolve.apply(pr, a);
}
that.go.apply(that, [end].concat(args));
});
};
Middleware.prototype.go = function(next) {
let args = Array.prototype.slice.call(arguments, 1);
next.apply(this, args); // This acts as a seed to the stack-chain
};
Middleware.prototype.use = function(fn) {
let self = this;
this.go = (function(stack) {
return function(next) {
// capture args passed to the stack function and proxy them to the user-supplied handler
let args1 = Array.prototype.slice.call(arguments, 1);
stack.apply(self, [function() {
let args2 = [].slice.call(arguments); // get only params and no callee details from arguments
args2.push(next.bind(self)); // the next middleware
fn.apply(self, args2);
}].concat(args1));
}.bind(this);
})(this.go);
};
// Inspired by: https://github.com/kolodny/exercises/tree/master/middleware
import Middleware from "./Middleware"
var middleware = new Middleware();
middleware.use(function(a, next) {
setTimeout(function() {
console.log(a);
next("something");
}, 10);
});
middleware.use(function(something, next) {
console.log(something);
next("END");
});
middleware.exec("anything").then(function(e){
console.log(e);
});
/*
* Logs:
* anything
* something
* end
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment