condition-middleware
v1.1.0
Published
Conditional middleware
Downloads
396
Maintainers
Readme
$ npm install --save condition-middleware
Right now error middlewares are not accepted inside a condition middleware.
The modifications done to the request inside a condition middleware will maintain in all the next middlewares,, including the ones outside the condition.
The middlewares can be passed to the condition in two different ways, the firs one is passing multiple list of middlewares and the second option is passing an object with multiple keys and values as a list of middlewares.
When passing multiple list of middlewares, then you can in the condition returns a boolean or a number.
Return a boolean
import condition from 'condition-middleware';
const isAdmin = (req) => {
return req.user.role === 'admin' ? true: false;
}
express().get(
'/',
initialMiddleware,
condition(isAdmin)(
[validateRequestAdmin, otherMiddlewareAdmin], // true
[validateRequestOthers] // false
),
otherMiddlewares,
finalMiddleware,
errorMiddleware
);
Returns a number
import condition from 'condition-middleware';
const getRoleCondition = (req) => {
const role = req.user.role;
if(role === 'admin'){
return 0
} else if(role === 'supervisor') {
return 1
} else {
return 2
}
}
express().get(
'/',
initialMiddleware,
condition(getRoleCondition)(
[validateRequestAdmin, otherMiddlewareAdmin], // 0
[validateRequestSupervisor], // 1
[validateRequestOthers] // 2
),
otherMiddlewares,
finalMiddleware,
errorMiddleware
);
When passing an object with a list of middlewares, then you can return in the condition any stuff that you are using in the object. If the value returned in the condition is not found in the object, then no middleware inside the condition middleware will be executed.
import condition from 'condition-middleware';
const getRoleCondition = (req) => {
const role = req.user.role;
if(role === 'admin'){
return 'admin'
} else if(role === 'supervisor') {
return 'supervisor'
} else {
return 'others'
}
}
express().get(
'/',
initialMiddleware,
condition(getRoleCondition)(
{
admin: [validateRequestAdmin, otherMiddlewareAdmin],
supervisor: [validateRequestSupervisor],
others: [validateRequestOthers]
}
),
otherMiddlewares,
finalMiddleware,
errorMiddleware
);
You can also nest the condition middleware inside other condition middlewares, using the different ways of use.
import condition from 'condition-middleware';
express().get(
'/',
initialMiddleware,
condition(isAdmin)(
[validateRequestAdmin, condition(hasCustomValue)(
{
value1: [performAnyOperation1],
value2: [performAnyOperation2],
}
)],
[validateRequestOthers]
),
otherMiddlewares,
finalMiddleware,
errorMiddleware
);
Right now it only can be used with express.