Saturday, 27 May 2017

Pass parameters from router to controller in ExpressJS

I have a route that is defined as such

router.route('/:id/organisers').get(HackathonControllers.getHackathonRoles());

Now, the getHackathonRoles is a controller defined as such for example:

function getHackathonRoles(role, req, res, next) {
    console.log(role);
    res.status(200).json({
        message: `Successfully updated Hackathon ${hackathonId}, published status updated to ${hackathonPublishedStatus}`
    })
}

What I ideally want to do is pass in a role by defining multiple router endpoints. Something like:

router.route('/:id/organisers').get(HackathonControllers.getHackathonRoles(role='organiser'));

And

router.route('/:id/volunteer').get(HackathonControllers.getHackathonRoles(role='volunteer'));

So basically I want to reuse the getHackathonRoles method and want to avoid rewriting the same method for different roles. I ideally, I should be able console.log(role) in the controller.

As of now, this fails and I get the error:

router.route('/:id/organisers').get(_hackathonController2.default.getHackathonRoles(role = 'organiser'));

How do I work around this and keep it sort of DRY? I don't want to incorporate parameters into the endpoint like /:id/? and the arguments are like role=organiser or role=volunteer etc.



via bholagabbar

No comments:

Post a Comment