我正在使用带有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使用相同的功能,但表名只会改变。
答案 0 :(得分:1)
您可以创建两个使用常见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逻辑与路由处理程序分开,所以改为有一个函数处理db并发回响应,有一个函数包含db逻辑,然后在route handle中使用该结果发送你的响应。这将使您的代码易于理解,易于测试并避免冗余。
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);})
});