I had some issues with async calls, but after understanding event-driven functions in Node a bit better, I have the following code. It basically does 2 SQL queries. The first checks to see if an existing phone number is in the table. If there is, nothing happens. If there isn't, then it runs a second query to add a new value into the table.
Currently it's event-driven, but .. how do I re-design it so that the outer function query is a separate function, and can even be used as a validation check for code elsewhere? (basically turning it into a generic helper function)?
router.post('/', function(req, res){
var mysql = req.app.get('mysql');
//values for 1st query - initial check
var customerCheck = "SELECT phone_number FROM customer WHERE phone_number=?";
var phoneNumberCheck = [req.body.phone_number];
//values for after 1st query validation passes
var sql = "INSERT INTO customer (name, phone_number, points, is_activated) VALUES (?,?,?,?)";
var inserts = [req.body.name, req.body.phone_number, 0, true];
mysql.pool.query(customerCheck, phoneNumberCheck, function(error, results, fields){
if(error){
console.log("Failed to verify!");
res.write(JSON.stringify(error));
res.end();
}else{
console.log(results);
if(results.length){
console.log("phone number exists, not adding.");
res.redirect('/view_customers');
}else{
mysql.pool.query(sql,inserts,function(error, results, fields){
if(error){
console.log("Failed to insert customer to DB!");
res.write(JSON.stringify(error));
res.end();
}else{
res.redirect('/view_customers');
}
});
}
}
});
});