Reputation: 1892
I am using node with express.
I have two rest api, the difference between the api is only database table only.
API - 1 http://localhost/test1
API - 2 http://localhost/test2
Both are post methods,
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);
}
Note: I need to use same function for both api but the table name only will be change.
Upvotes: 0
Views: 325
Reputation: 7920
You can create two function which utilizes common findAll
method like following:
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);
But I would suggest you to separate your db logic from route handler, so instead having one function which handles db and send response back, have one function which contains db logic, then in the route handle use that result to send your response. This will make your code easy to understand, easy to test and avoid redundancy.
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);})
});
Upvotes: 1