I have a node.js/express.js app which I am getting caught in callback hell when it comes with handling the Response to the screen.
In express I have app.post('/file-upload', returnUploadDetails);
and this accepts a CSV file.
The plan is to get the file, read through each row insert/update tables, and report back errors/success to the screen. The problem is that I want to return all the feedback to the screen and can't find the best way to do it so generally need some pointers. Once I've called returnUploadDetails(req,res) should I be passing that through to my other callback, should I just be updating a single variable, or is there something fundamental I am missing?
Here is the module I've created (i've skipped the "require" block)
var appMySql = {
init : function() {
// create MySQL Connection
var connection = mysql.createConnection(settings.mysql);
connection.connect();
return connection;
},
returnUploadDetails : function(req, res) {
if (req.files.csvf.size === 0) {
return next(new Error("Hey, first would you send a file?"));
}
fs.readFile(req.files.csvf.path, function(err, data) { // Read the contents of the file
if (err) console.error("** ERROR ** ", err);
else appMySql.parseCSV(data.toString(), appMySql.processFile); // Finally parse the data
});
} // end returnUploadDetails
insertUser : function(userRecord, myKeyid, callback) {
var connection = appMySql.init();
var qry = connection.query('INSERT INTO users SET ?', [userRecord],
function(err, result) {
if (err) {
var msg = '** ERROR **' + err;
console.error(msg);
return;
} else {
connection.end();
callback(result.insertId, myKeyid);
}
});
}, // End insertUser
updateKey : function(newUserId, myKeyID) {
var connection = appMySql.init();
connection.query(
'SELECT * FROM keys WHERE concat(key_prefix,key_number) LIKE ?', [
mykeyID
], function(err, result) {
if (err) {
console.error( '** ERROR **' + err );
return;
}
if (result.length == 0) console.error('** ERROR ** Key ' + myKeyID + ' NOT VALID');
connection.end();
});
}, // End UpdateKey
processFile : function(err, data) {
if (err) console.error("** ERROR ** ", err);
else processRecord(data); // Dump the CSV to the console window
}, // End processFile
parseCSV : function(csvData, callBack, req, res) {
parse(csvData, {comment : '#'}, callBack)
},
processRecord : function (data) {
data.forEach(function(record) {
var d = new Date(),
today = d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() +
" " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
var recordData = {
user_username: record[5],
user_password: '',
user_firstname: record[1],
user_lastname: record[2],
user_email: record[5],
user_mobile: record[6],
user_telephone: record[6]
};
// Use the connection
appMySql.insertUser(recordData, record[4], appMySql.updateKey);
});
}
};
module.exports = appMySql;