Being new to Node's way of doing things, I am quite confused about how to do what seems to be a trivial use-case:
e.g.
var userName = req.body.username;
var userPwd = crypto.hash(req.body.password);
var user = db.getUser(userName, userPwd);
if (user.id) {
console.log("valid login entered");
} else {
console.log("INVALID login entered");
}
the db.getUser fn is in a separate file called "db.js". the code in that file is as follows:
var pg = require("pg");
var conString = "pg://<connection string to PostgreSQL DB>";
var client = new pg.Client(conString);
client.connect();
exports.response = [];
exports.getUser = function(username, password) {
var query = "SELECT id, first_name, last_name FROM usertable where login = $1 and password = $2";
var query = client.query({
text: query,
values: [username, password]
});
query.on("row", function (row) {
console.log("Returned row from getUser query:" + row.id + " and fname:" + row.first_name + " and lname:" + row.last_name);
response.push(row);
return response;
});
query.on("end", function (result) {
client.end();
});
};
due to the callback mechanism, the code enters the "INVALID login entered" debug stmt before the query is done executing.
I guess my main question is: if i want to keep all the DB query code in a separate include file (as opposed to cluttering up the main controller file with that code), how can i ensure that the DB function finishes running and returns a value to the calling code, before the rest of the code executes?
Ok, found the answer (at least, an answer; there might be more ways to do this better).
I changed the calling code from:
var user = db.getUser(userName, userPwd);
to:
var user = db.getUser(userName, userPwd, function(response) {
console.log("USER INFO:");
console.log(response, null, " ");
});
and modified the db.getUser function from:
exports.getUser = function(username, password) {
var query = "SELECT id, first_name, last_name FROM usertable where login = $1 and password = $2";
var query = client.query({
text: query,
values: [username, password]
});
query.on("row", function (row) {
console.log("Returned row from getUser query:" + row.id + " and fname:" + row.first_name + " and lname:" + row.last_name);
response.push(row);
return response;
});
query.on("end", function (result) {
client.end();
});
};
to:
exports.getUser = function(username, password, callback) {
var query = "SELECT id, first_name, last_name FROM usertable where login = $1 and password = $2";
var query = client.query({
text: query,
values: [username, password]
});
query.on("row", function (row) {
console.log("Returned row from getUser query:" + row.id + " and fname:" + row.first_name + " and lname:" + row.last_name);
response.push(row);
return callback(response);
});
query.on("end", function (result) {
client.end();
});
That did the trick ! : ) . Please do let me know if this approach is acceptable, or whether there's a better way of doing it.