Middleware usage with extra arguments
See original GitHub issueOn the optional arguments to an Express.js middleware , probaly a fourth one apart from being an error handling middleware and at ideal many arguments without any Express.js specific limit, I have a logic where it comes useful. It may be achieved by a different way, but anyways. But this is not data passing between middleware, maybe this question should have its own post. I have already suggested some solutions for this, and osme what I was guessed of, however, this can be taken as a design suggestion for bettering the Express.js middleware use pattern. Thanks in advance.
I want to make some api routes permission checked, the middleware I wish to write should look up database for a requesting user for how many reputation points (integer) he/she has. I defined an object to hold privileges and reputation points required as key value pairs. Later, middleware should look up this privileges object to see if the user has greater than or equal reputation points for a corresponding action. I want to pass this corresponding action name which is a key in the privileges object as a different string for each route.
By the way, apparently I also need route based (not Router based) middleware mounting, I am not sure if Express.js supports, but this is another story.
Maybe one can describe and ask this use case as can I parametrize a middleware function with my parameters, not just by incoming req and res objects?
/// Privilege Check middleware
// used per route with corresponding actionName
// signature function (request, response, next, actionNameOneOfKeysInPrevilegesObject::String)
var privilegeCheck = function (req, res, next, actionName) {
db.one(
`
SELECT reputation FROM users WHERE id = $(id)
`,
{id: req.user.id} // remember req.user was set by jwt.sign(data) during login or signup with demanded data; here it is {id:, name:, username:,}
)
.then(function (data) {
if(data >= privileges[actionName]) {
next();
}
else {
res.status(403).json({errorMessage: "You need to have " + privileges.questionUpvote + " reputation to upvote."});
}
})
.catch(function (error) {
console.error(error);
})
};
// reputations needed for privileged actions
var privileges =
{
questionAsk: 5,
answer: 15,
acceptAnswer: 0,
comment: 5,
questionEdit: 20,
answerEdit: 20,
commentsEdit: 0,
postsUpvote: 30,
postsDownvote: 30,
commentsUpvote: 5,
questionUpvote: 10,
questionDownvote: 125,
}
Issue Analytics
- State:
- Created 7 years ago
- Comments:5 (2 by maintainers)
I don’t think this is a valuable use-case, you should probably be treating
req
as the application “context” for passing things onward. In what case do you need this? I can’t tell from your example whereactionName
comes from.Edit: Assuming this is defined based on a previous route passing the property, you can just write a function that returns a function:
this can be closed now i think