I have a node.js file which has methods that read and write from my heroku postgresql database. I am using the 'pg' module in order to access the DB. My problem is that calling my getSleepMode function more than once in a row causes the ECONNRESET error. This function simply sends a query to my DB and retrieves an integer. I understand it might be because node.js functions are non-blocking, and both instances of getSleepMode() are trying to access my DB at the same time. But wouldn't this pose as a problem if more than one client is trying to get data from my DB at the same time? Assuming my heroku postgresql db can handle queries from multiple clients at the same time, shouldn't this still work? I have relevant parts of the code below:
[database connection variables omitted]
var pg = require("pg")
var conString = "pg://" + USER + ":" + PW + "@" + HOST + ":" + PORT + "/" +
DATABASE + "?ssl=true";
var client = new pg.Client(conString);
/*This function accesses my database and retrieves an integer field
called "sleepmode"*/
function getSleepMode(username) {
var query = "SELECT sleepmode FROM \"Users\" where username='" +
username + "';";
connectWrapper(query, function(err,result) {
if (err) {
return console.err("Error getting sleep mode", err);
}
client.end();
console.log("sleepmode " + result.rows[0].sleepmode);
});
}
/*This function is here so I can reuse it for more than just
my getSleepMode() function*/
function connectWrapper(query, handler) {
client.connect(function(err) {
if (err) {
return console.error('could not connect to postgresq',err);
}
client.query(query, handler);
});
}
getSleepMode("username1"); //This ALONE works
getSleepMode("username2"); //but when this line follows, i get the error
Running this causes this output:
$user: node dbconnect.js
could not connect to postgresq { [Error: write ECONNRESET] code: 'ECONNRESET', err
ECONNRESET', syscall: 'write' }
could not connect to postgresq { [Error: write ECONNRESET] code: 'ECONNRESET', err
ECONNRESET', syscall: 'write' }
Events.js:72
throw er; // Unhandled 'error' event
^
Error: write ECONNRESET
at errnoException (net.js:904:11)
at Socket._write (net.js:645:26)
at doWrite (_stream_writable.js:225:10)
at writeOrBuffer (_stream_writable.js:215:5)
at Socket.Writable.write (_stream_writable.js:182:11)
at Socket.write (net.js:615:40)
at write (_stream_readable.js:601:24)
at flow (_stream_readable.js:610:7)
at _stream_readable.js:578:7
at process._tickCallback (node.js:419:13)
But when I run it so that getSleepMode() is called only once, there is no error and it works as expected.
$user: node dbconnect.js
sleepmode 1