title: Retry connection postgres Nodejs
body: <p>I am using a postgres database for my express web server.
  I am using the 'pg' library to execute queries on this database.</p>
  <p>Here is my connection method :</p>
  <pre><code>const db = new Client({
      user: 'xxx',
      host: 'xxx',
      database: 'xxx',
      password: 'xxx',
      port: xxx,
  })
  db.connect(err =&gt; {
      if (err) {
          console.error('connection error', err.stack)
      } else {
          console.log('connected')
      }
  </code></pre>
  <p>Then to execute a request I do this:</p>
  <pre><code>db.query(MY_REQUEST, function (err, data) {
              if (err) throw err;
              res.render('hello/world', {
                  title: 'Hello',
                  data: data.rows
              });
          });`
  </code></pre>
  <p>It all works perfectly. But after several minutes without using my website, my connection to the db times out, and I get the following error:</p>
  <pre><code>node:events:355
  throw er; // Unhandled 'error' event
         ^
  Error: Connection terminated unexpectedly
  at Connection.&lt;anonymous&gt; (/usr/src/app/node_modules/pg/lib/client.js:132:73)
  at Object.onceWrapper (node:events:484:28)
  at Connection.emit (node:events:378:20)
  at Socket.&lt;anonymous&gt; (/usr/src/app/node_modules/pg/lib/connection.js:58:12)
  at Socket.emit (node:events:378:20)
  at TCP.&lt;anonymous&gt; (node:net:665:12)
  Emitted 'error' event on Client instance at:
  at Client._handleErrorEvent (/usr/src/app/node_modules/pg/lib/client.js:319:10)
  at Connection.&lt;anonymous&gt; (/usr/src/app/node_modules/pg/lib/client.js:149:16)
  at Object.onceWrapper (node:events:484:28)
  [... lines matching original stack trace ...]
  at TCP.&lt;anonymous&gt; (node:net:665:12)
  </code></pre>
  <p>How could I do to reconnect automatically when the connection is cut or when a request fails?</p>