middleware-orchestrator
v1.0.0
Published
I'm excited to introduce a new way to handle controlled execution of middleware stacks in Express.js by providing logical OR and AND features. This package is designed to simplify middleware management by removing the need for on-demand middleware that of
Downloads
4
Readme
Middleware-Orchestrator
I'm excited to introduce a new way to handle controlled execution of middleware stacks in Express.js by providing logical OR and AND features. This package is designed to simplify middleware management by removing the need for on-demand middleware that often requires combining the logic of two or three existing middleware functions using logical operators. Such combinations create redundancy and make middleware management cumbersome.
Features
Currently, my package is slightly opinionated, offering boilerplate code. However, we plan to release future versions with more customizable and non-opinionated features, making the package even more flexible and powerful.
Converting a Normal Middleware to Promise-Based Middleware
To make the most of my package, it's important to understand how to convert a standard middleware into one that returns a promise. Below is an example:
Original Middleware
const validation = require("../utils/Validation");
const Validation = new validation();
export const isLead = (req, res, next) => {
const User = Validation.getUser(req.cookies.jwt);
if (User && User.role === process.env.LEAD) {
next();
} else {
res.status(403).json({ message: "Unauthorized User" });
}
}
Converted Middleware (Returning Promises)
const validation = require("../utils/Validation");
const Validation = new validation();
export const isLead = (req, res) => {
return new Promise(async (resolve, reject) => {
try {
const User = await Validation.getUser(req.cookies.jwt);
if (User === null) {
return reject({ status: 400, message: "User not found" });
}
if (User.role == process.env.LEAD) {
resolve();
} else {
return reject({ status: 403, message: "Unauthorized User" });
}
} catch (err) {
return reject({ status: 500, message: "Internal Server Error" });
}
});
}
Code Usage
const { getOR, getAnd, getAndPromise, single } = require('middleware-orchestrator');
router.post("/edit/:id",
upload.fields([
{ name: 'testcase', maxCount: 1 },
{ name: 'answer', maxCount: 1 }
]),
getOR([
getAndPromise([rbacMiddleware.execute("update_problem"), PDP.execute]),
getAndPromise([ethicalWallPolicy.execute("update_problem"), PDP.execute])
]),
problemController.editProblem
);
getOR and getAND
These are outter functions which will not be wrapped inside any other getOR/getAND
getORPromise and getAndPromise
Thse are the inner functions which will be wrapped inside any of the getOR/getAND according to the requirements