I'm trying to use the recommendation of the creator of node-postgres and separate the database call as a separate file. This will enable both scaling and consolidation of the various, boilerplate query types. Unfortunately, brianc's explanation of how to do this does not work for me. The "cb(err, result)" throws an error.
This is my test boilerplate database call (db.js):
var pg = require('pg');
var connectionString = 'postgres://postgres:password@10.10.10.10:5432/MyDatabase';
var client = new pg.Client(connectionString, function(){
if (err) {
console.log(err);
}
});
var querytext = 'Select addr_type, addr_descr FROM ref_addr_type;';
var result = [];
var resultset = [];
client.on('drain', client.end.bind(client));
client.connect();
module.exports = {
query: function(callback) {
var query = client.query(querytext, function(callback){
var resultsset = query.on('row', function(row, result) {
result.addRow(row);
query.on('end', function(res) {
client.end(function (err) {
if (err) throw err;
});
console.log("JSON rows1: " + JSON.stringify(res));
return res;
});
console.log("JSON rows2: " + JSON.stringify(result));
return result;
});
console.log(resultset.length + ' rows were received');
callback = resultsset;
console.log("JSON3 rows: " + JSON.stringify(resultsset, null, ' '));
console.log("JSON4 rows: " + resultsset[0]);
return callback;
})
}
}
This is the script calling it (call.js):
var db = require('../db');
var items = [];
items = db.query();
console.log("Main db: " + items);
console.log("Main db json: " + JSON.stringify(items));
console.log("Main db inspect: " + util.inspect(items));;
This is the console output:
0 rows were received
JSON3 rows: {
"text": "Select addr_type, addr_descr FROM ref_addr_type;",
"portal": "",
"_result": {
"command": "SELECT",
"rowCount": 5,
"oid": null,
"rows": [
{
"addr_type": "2",
"addr_descr": "Home"
},
{
"addr_type": "3",
"addr_descr": "Institution"
},
{
"addr_type": "1",
"addr_descr": "Company"
},
{
"addr_type": "8",
"addr_descr": "Organization"
},
{
"addr_type": "10",
"addr_descr": "Government"
}
],
"fields": [
{
"name": "addr_type",
"tableID": 17549,
"columnID": 1,
"dataTypeID": 20,
"dataTypeSize": 8,
"dataTypeModifier": -1,
"format": "text"
},
{
"name": "addr_descr",
"tableID": 17549,
"columnID": 2,
"dataTypeID": 1043,
"dataTypeSize": -1,
"dataTypeModifier": -1,
"format": "text"
}
],
"_parsers": [
null,
null
],
"rowAsArray": false
},
"isPreparedStatement": false,
"_canceledDueToError": false,
"_promise": null,
"domain": null,
"_events": {},
"_eventsCount": 1
}
JSON4 rows: undefined
As you can see, there is no console.log output within call.js ("Main db:, Main db json:" and "Main db inspect:"). Also, no rows are counted in "resultset" and I can't get any results from the JSON4 array.
I've spent 4 days on this and am probably making a bunch of rookie mistakes. Please provide some guidance on getting the db.js to deliver the values to call.js.