Creating a expressjs middleware that accepts parameters
I am trying to create a middleware that can accept parameters. How can this be done?
example
app.get('/hasToBeAdmin', HasRole('Admin'), function(req,res){
})
HasRole = function(role, req, res, next){
if(role != user.role){
res.redirect('/NotInRole);
}
next();
}
function HasRole(role) {
return function(req, res, next) {
if (role !== req.user.role) res.redirect(...);
else next();
}
}
I also want to make sure that I don't make multiple copies of the same function:
function HasRole(role) {
return HasRole[role] || (HasRole[role] = function(req, res, next) {
if (role !== req.user.role) res.redirect(...);
else next();
})
}
app.get('/hasToBeAdmin', (req, res, next) => {
hasRole(req, res, next, 'admin');
}, (req,res) => {
// regular route
});
const hasRole = (req, res, next, role) => {
if(role != user.role){
res.redirect('/NotInRole');
}
next();
};
Alternatively if you do not have too many cases or if role is NOT a string:
function HasRole(role) {
return function (req, res, next) {
if (role !== req.user.role) res.redirect(/* ... */);
else next();
}
}
var middlware_hasRoleAdmin = HasRole('admin'); // define router only once
app.get('/hasToBeAdmin', middlware_hasRoleAdmin, function (req, res) {
})