Last active
December 9, 2017 04:45
-
-
Save jamischarles/201c1aa098720a6e3f7ea9c103f694de to your computer and use it in GitHub Desktop.
Simple example showing how to chain functions similar to how middleware is chained in express.js
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
// simple example of how to create a function that calls a middleware chain, similar to express middleware | |
var req = {type: "req"}; | |
var res = {type: "res"}; | |
// 3 middlewares | |
var first = function(req, res, next) { | |
req.first = true; //easy way to verify that all have been executed | |
res.first = true; | |
return next(); | |
} | |
var second = function(req, res, next) { | |
req.second = true; | |
res.second = true; | |
return next(); | |
} | |
// this one is last | |
var last = function(req, res) { | |
console.log('End of middleware reached'); | |
console.log('req', req); | |
console.log('res', res); | |
} | |
// Starts with last function in the array, and binds params (req,res) and "next" fn if available | |
// Iterates through fns array backwards binds to the next until it reaches the beginning of the fns array | |
// @params you want to pass to each one | |
// @functions in the middleware chain | |
// @returns a function that starts it all | |
function chainMiddleware(params, ...fns) { | |
return fns.reduceRight(function(prev, curr) { | |
return curr.bind(null, ...params, prev); // bind req,res, next for last() then second() then first() | |
}, null) // null forces req,res to be bound to last() properly (w/o next) | |
} | |
var start = chainMiddleware([req, res], first, second, last); | |
start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment