Skip to content

Instantly share code, notes, and snippets.

@HappyZombies
Created July 30, 2021 22:13
Show Gist options
  • Save HappyZombies/9a7dde070a90bc53066be0841e8c3904 to your computer and use it in GitHub Desktop.
Save HappyZombies/9a7dde070a90bc53066be0841e8c3904 to your computer and use it in GitHub Desktop.
Middleware method that will chain and optionally run other middlewares given a condition
const express = require('express');
const app = express();
const dynamicMiddlewareAddition = async (req, res, next) => {
const number = Math.round(Math.random() * 100);
const isEven = number % 2 === 0;
//given a condition, run certain middlewares chained to one another.
const middlewares = isEven ? [middleware2] : [middleware1, middleware2, middleware3];
console.log(number, isEven, middlewares);
if(middlewares.length >= 1) {
const combinedMiddleware = (index) => {
if(index === middlewares.length) {
return next();
}
const middleware = middlewares[index];
middleware(req, res, () => combinedMiddleware(index + 1));
}
return combinedMiddleware(0);
}
return next();
};
const middleware1 = (req, res, next) => {
console.log("Middleware 1");
return next();
}
const middleware2 = (req, res, next) => {
console.log("Middleware 2");
return next();
}
const middleware3 = (req, res, next) => {
console.log("Middleware 3");
return next();
}
app.use(dynamicMiddlewareAddition);
app.listen(1000, () => {
console.log("listening! Go to localhost:1000 and see the middlewares log differently if the generated number is even or not.");
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment