0

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.

1 Answer 1

1

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);})
});
Sign up to request clarification or add additional context in comments.

7 Comments

if I am wrong means please correct me. need to create function for each db results ?
or please provide one example. I didn;t get "findAllFromDB"
Db logic depends on to which db you are using and which ORM library you are using. But in general yes for each different resource you should generate one helper function.
sorry, Please provide the example.
function findAllUsers(){return db.Users.findAll()} // using sequelize docs.sequelizejs.com/en/v3
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.