hooge
hooge

Reputation: 25

Passing parameters to express middleware in routes

I am building a nodejs + express RESTful server, and am trying to leverage middleware to ease authorization of specific actions.

What I am trying to achieve is to pass parameters to my authorization middleware functions. I was wondering if it is at all possible to do this in the routes or if I have to extract the parameters in the middleware function. I was hoping to avoid that behavior as I have been *hum* not entirely consistent in my URL parameter names.

What I would like to do is something like this:

router.get(
    '/:productId', 
    auth.can_get_this_product(productId), // Pass the productId here
    controller.perform_action_that_requires_authorization
);

But this is not possible. Because I have other routes where the names of parameters might not be the same (ie: router.get(/:p_id, auth.can_get_thi...). I realize I should probably just go back and make sure that my parameter names are consistent everywhere and retrieve the parameters in the middleware using req.param('productId')but I am curious if it would be at all possible.

Upvotes: 1

Views: 2408

Answers (1)

panta82
panta82

Reputation: 2721

Well, I suppose you can pass the params hash key and then use that.

router.get(
    '/:productId', 
    auth.can_get_this_product('productId'), // Pass the productId *KEY* here
    controller.perform_action_that_requires_authorization
);

//....

function can_get_this_product(productIdKey) {
    var productId = req.params[productIdKey];
    //....
}

But of course, we both know you should just bite the bullet and refactor those names.

Upvotes: 1

Related Questions