Reputation: 59
I have a question about if it is right to do two client.queries one right after the other. I am trying to build a REST API. Example:
client.query("select waiters_id from waiters", function(err, result){
if(err){
res.json({success: false, msg: "error"});
}
if(result.rows.length === 0){
done();
res.json({success: false, msg: "error"});
} else{
if(results.rows[0].waiter_id === req.body.waitid){
done();
res.json({success: true, msg: "proceed"});
}
client.query("insert into waiters",function(err, result){
// MORE CODE
});
I am trying to check if there is a waiter in the waiters table, then insert some specific information into that waiter in that waiters table if there is a waiter. If there is a better way to do this please let me know. I don't want to lose performance. Thanks
Upvotes: 0
Views: 58
Reputation: 10491
This question really has more to do with SQL then nodejs/express. SQL provides you with the ability to use if statements to make logical assertions about your results:
client.query(
"IF EXISTS (SELECT * FROM waiters WHERE waiters_id='SomeValue')
UPDATE waiters SET (...) WHERE waiters_id='SomeValue'
ELSE
INSERT INTO waiters VALUES (...)
SELECT * FROM waiters",
function (err, result) {
// do something with results here
}
);
Which is essentially the same control logic you are trying to build with nodejs. Using the above would eliminate the need for another query.
Upvotes: 1