expressJS中的嵌套路由
nested routes in expressJS
我定义了以下路由
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
})
})
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
})
}
});
})
我定义了以下路由
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
})
})
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
})
}
});
})