Skip to content

Instantly share code, notes, and snippets.

@chartjes
Created March 9, 2012 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chartjes/2007400 to your computer and use it in GitHub Desktop.
Save chartjes/2007400 to your computer and use it in GitHub Desktop.
I have my model here:
// transactionmodel.js
function TransactionModel() {
var pg = require('pg');
var connectionString = "pg://chartjes:******@localhost:5432/ibl_stats";
this.client = new pg.Client(connectionString);
this.client.connect();
this.getCurrent = function() {
var startDate = "(SELECT MAX(transaction_date) FROM transaction_log)-'3 weeks'::interval)";
var endDate = "(SELECT MAX(transaction_date) FROM transaction_log)";
var q = "SELECT * " +
"FROM transaction_log " +
"WHERE log_entry LIKE 'Trades%' " +
"AND transaction_date >= (SELECT MAX(transaction_date) FROM transaction_log)-'3 weeks'::interval " +
"AND transaction_date <= (SELECT MAX(transaction_date) FROM transaction_log) " +
"ORDER BY trans_id DESC ";
var transactions = [];
this.client.query(q, function (err, result) {
if (err) {
console.log(err);
return {'success': 'false', 'msg': err};
}
var idx = 0;
while (idx < result.rows.length) {
transactionId = result.rows[idx].trans_id;
team1 = result.rows[idx].ibl_team;
team2 = result.rows[idx + 1].ibl_team;
description = team1 + ' ' + result.rows[idx].log_entry;
transactionDate = result.rows[idx].transaction_date;
idx = idx + 2;
transaction = {
'id': transactionId,
'tradePartner1': team1,
'tradePartner2': team2,
'description': description,
'date': transactionDate
};
transactions.push(transaction);
}
});
return transactions;
};
}
module.exports.TransactionModel = TransactionModel;
and I have my "front controller" in express calling it like this:
app.get('/transactions/current', function(req, res) {
var currentTransactions = tm.getCurrent();
return res.send(currentTransactions);
});
I am probably misunderstanding something fundamental here but I am wondering why I am not seeing any value in currentTransactions when I see output inside TransactionModel.getCurrent()?
@markstory
Copy link

transactions is an empty array when tm.getCurrent() completes. You'd need to make that function accept a callback to call when the query is complete.

var callback = function (results) {
    res.send(results);
};
tm.getCurrent(callback);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment