节点+回调函数传递参数
问题描述:
我正在使用express的节点。节点+回调函数传递参数
我有两个休息api,api之间的区别只是数据库表而已。
API - 1种 http://localhost/test1
API - 2 http://localhost/test2
两者都是交方法,
router.post('test1', findAll);
router.post('test2', findAll);
function findAll(req, res){
//Here test1 api result get from different db table.
//Here test2 api result get from different db table.
How can I sent the db table name in parameters?
//Here have logic in db and return results.
res.send(spec.resp);
}
注:我需要使用相同的功能,两个API,但表名只会改变。
答
您可以创建两种功能,采用常见的findAll
方法类似以下内容:
function findAllFromTable1(req, res, next){
return findAll("table1", req, res, next);
}
function findAllFromTable2(req, res, next){
return findAll("table2", req, res, next);
}
function findAll(tableName, req, res, next){
//db logic
res.send(spec.resp);
}
router.post('test1', findAllFromTable1);
router.post('test2', findAllFromTable2);
但我建议你到你的数据库逻辑从路由处理分开,这样反而有一个功能,处理数据库,并发送回响应,有一个包含db逻辑的函数,然后在路径句柄中使用该结果发送您的响应。这将使您的代码易于理解,易于测试并避免冗余。
function findAllFromDB(){
//db logic
return dbResult; // returns a promise since db operations are async.
}
router.post('test1', function(req, res, next){
findAllFromDB
.then(function(dbResult){res.send(dbResult)})
.catch(function(err){ res.status(500).send(err);})
});
如果我错了意味着请纠正我。需要为每个db结果创建函数? – RSKMR
或请举一个例子。我没有;“getAllFromDB” – RSKMR
Db逻辑取决于你正在使用哪个数据库和你正在使用哪个ORM库。但总的来说,对于每种不同的资源,您都应该生成一个辅助函数。 – cubbuk