Node-postgres: How to reconnect pg.Client after restart Postgres

Created on 13 Jan 2018  Â·  1Comment  Â·  Source: brianc/node-postgres

I have code like this:

`const dbadmconn = new pg.Client(config.dbadmconn);
dbadmconn.connect()
.then(() => {
return "successfully connected to admindb";
})
.catch((e) => {
e.message = "not possible to connect for user dbadmconn";
return Promise.reject(e);
});

dbadmconn.on("error", (err) => {
console.log("dbadmconn");
console.log(err.stack);
});
`

My question is: How to reconnect dbadmconn pg.Client after restart Postgresql?
After: sudo service postgresql stop , err.stack is outputed to console.
And If I then do sudo service postgresql start, pg.Client returns nothing from database. Is sleeping.

question

Most helpful comment

After the 'error' event, the client is invalid; create a new one.

let dbadmconn;

function connect() {
    dbadmconn = new pg.Client(config.dbadmconn);
    dbadmconn.on('error', error => {
        // â‹®
        connect();
    });
    return dbadmconn.connect();
}

connect();

A pg.Pool will handle this for you, even if you never want more than one client.

>All comments

After the 'error' event, the client is invalid; create a new one.

let dbadmconn;

function connect() {
    dbadmconn = new pg.Client(config.dbadmconn);
    dbadmconn.on('error', error => {
        // â‹®
        connect();
    });
    return dbadmconn.connect();
}

connect();

A pg.Pool will handle this for you, even if you never want more than one client.

Was this page helpful?
0 / 5 - 0 ratings