expressJS中的嵌套路由

时间:2016-11-24 07:29:05

标签: javascript express nested-routes

我定义了以下路线

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
})

如何合并这两条路线,只调用一次数据库来获取公司数据。基本上我只是想重用那个逻辑。

我正在寻找类似的东西(经过测试但不起作用)

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
    })

})

1 个答案:

答案 0 :(得分:3)

  

有一个共同的功能来为您获取该数据。保持路线分开!

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
      })
    }
  });
})