DroopyTersen
10/19/2016 - 10:22 PM

middleware.js

var middlewarify = function(pre, post) {
    post = post || function(next) { next() }

  	var doIt = function(next, params) {
    	return pre(next, params); 
    }

    var func = function(params) {
        func.use(post)
        return new Promise((resolve, reject) => {
    	    doIt((result) => {
                resolve(result)
            }, params);
        })
    };

    func.use = function(fn){  
       doIt = (function(oldDoIt) {
       		return function(next, params) {
            	oldDoIt(fn.bind(this, next), params);
            }
       })(doIt);
    };
  
	return func;
};

var preFunc = function(next, params) {
    setTimeout(() => {
        console.log("pre");
        console.log(params);
        next("from pre");
    }, 100);
}

var postFunc = function(next, params) {
    setTimeout(() => {
        console.log("post");
        console.log(params);
        next("from post")
    }, 100);
}

var middleware1 = function(next, params) {
    setTimeout(() => {
        console.log("Middeware 1");
        console.log(params);
        next("from m1")
    }, 100);
}
var middleware2 = function(next, params) {
    setTimeout(() => {
        console.log("Middeware 2");
        console.log(params);
        next("from m2")
    }, 100);
};

var doSomething = middlewarify(preFunc, postFunc);
doSomething.use(middleware1);
doSomething.use(middleware2);

doSomething("from init").then(params => {
    console.log("Done")
    console.log(params);
});