0

I have the following routes defined

router.get('/:company', function (req, res, next) {
    // 1. call database and get company data
    // 2. render company view
})

router.get('/:company/employees', function (req, res, next) {
    // 1. call database and get company data
    // 2. call database and get employees data
    // 3. render employees view
})

How can I merge these 2 routes to make only one call to the database to get company data. Basically I just want to reuse that logic.

I´m looking for something like this (tested but it doesn't work)

router.get('/:company', function (req, res, next) {
    // 1. call database and get company data
    // 2. render company view

    router.get('/:company/employees', function (req, res, next) {
        // no need to call database to get company data. we already have it
        // 1. call database and get employees data
        // 2. render employees view
    })

})
handsome
  • 2,335
  • 7
  • 45
  • 73
  • You can't nest routes. Doing so creates havoc. At first, the route is not even active until the parent route is hit first and then a new route handler (and thus a duplicate route handler) is installed every time the parent route is hit. Can't do it that way. Just move common code into a shared function which you can call from multiple routes. It's funny how the Express route handler architecture somehow makes people forget basic programming principles of putting common code into a shared function that can be called from multiple places. – jfriend00 Nov 24 '16 at 07:46
  • @jfriend00 — "_It's funny how the Express route handler architecture somehow makes people forget basic programming principles of putting common code into a shared function that can be called from multiple places._" :P – Rayon Nov 24 '16 at 07:55
  • yes is funny. ha ha ha. – handsome Nov 24 '16 at 16:34

1 Answers1

3

Have a common function to get that data for you. Keep routes separate!

function getCompanyData(input, cb) {
  //DB operation
  return cb(data);
}

function getEmployeeData(input, cb) {
  //DB operation
  return cb(data);
}
router.get('/:company', function(req, res, next) {
  getCompanyData({
    data: data
  }, function(err, data) {
    //reder view
  });
})

router.get('/:company/employees', function(req, res, next) {
  getCompanyData({
    data: data
  }, function(err, data) {
    if (!err) {
      getEmployeeData({
        data: data
      }, function(err, data) {
        //reder view
      })
    }
  });
})
Rayon
  • 36,219
  • 4
  • 49
  • 76
  • I suggest using the module `async` when working with multiple asynchromous call in one function and especially with the `waterfall` method. http://caolan.github.io/async/docs.html#waterfall – mxncson Nov 24 '16 at 08:54
  • @mxncson — I would say it "depends".. I would avoid `async` for such minor use-case.. – Rayon Nov 24 '16 at 08:55