Skip to content

Instantly share code, notes, and snippets.

@lesterzone
Last active October 1, 2017 05:02
Show Gist options
  • Save lesterzone/68a390777298549d65af76de57d84f3e to your computer and use it in GitHub Desktop.
Save lesterzone/68a390777298549d65af76de57d84f3e to your computer and use it in GitHub Desktop.
Dynamic middleware for Express
/**
* Apply custom middlewares to request
* Usage:
* 1- Identify that you require dynamic middlewares for your endpoint.
* 2- assign each middleware to a variable and push it to an array
* const middlewares = [middleware1, middlware2];
* 3- require this file with expected objects.
*
* Example:
* const middleware1 = require('some middleware file here');
* const middleware2 = require('another middleware file here');
*
* const middlewares = [middleware1, middleware2];
*
* function myCustomMiddlware(request, response, next){
* if(somethingCondition){
* return customMiddlware(middlwares, request, response, next);
* }
* return customMiddleware([middleware1], request, response, next);
* }
*/
'use strict';
const async = require('async');
/**
* middlewares: array of middlewares like require('a middleware file path')
* request: request object from express middleware
* response: response object from express middleware
* next: callback from express middleware
*/
function customMiddlewares(middlewares = [], request, response, next) {
/**
* Bind each middleware to current request|response object for the actual
* request to the endpoint
*/
let options = middlewares.map(item => item.bind(null, request, response));
/**
* Run each middleware defined and associated to current request, if any
* error, it will be handled by the `next` callback, also, on success or
* internally called `next` for each middleware, call the next one in a
* sequence
*/
return async.series(options, (error) => next(error));
}
module.exports = customMiddlewares;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment