technoSpino
technoSpino

Reputation: 510

What is the DRY approach for Nested Express Routes

I would like to have an api that allows the getting of nested attributes of a person

router.get('/person/:id', fun.. router.get('/person/:id/name, fun... router.get('/person/:id/address, fun...

All are the same object of one mongoose scheme. What is the best way to do the lookup of the person object? I feel I should be using router.use(/person/:id) to look the person and somehow pass it along.

Upvotes: 3

Views: 257

Answers (1)

victorkt
victorkt

Reputation: 14572

Check app.param(), for example:

router.param('id', function(req, res, next, id) {
  Person.find(id, function(err, person) {
    if (err)next(err);
    else if (person) {
      req.person = person;
      next();
    } else {
      next(new Error('failed to load person'));
    }
  });
});

router.get('/person/:id', function() { /* ... */});
router.get('/person/:id/name', function() { /* ... */});
router.get('/person/:id/address', function() { /* ... */});

Then you can access your Person object from req.person.

Upvotes: 4

Related Questions