When to close a postgres pool at Nodejs?

Asked

Viewed 370 times

0

I’m with a Nodejs application that basically has a food search engine. However always in the second research occurs the following exception and I do not know in what part of the code exactly I should open and close a connection with the bank.

(node:22204) UnhandledPromiseRejectionWarning: Error: Cannot use a pool after calling end on the pool

So is my code:

 try{
    let pool = require ('./conexao'); 
    let res = await pool.query("SELECT * FROM pesquisaAlimentos('?')", [str]);
    await pool.end();   
    return res.rows;
 }   catch(err){
    throw(err);
 }

The app.js is like this:

try {
        pesqAlimentos(pesq.barraPesq).then(result => {
            jsonRes = { "Alimentos" : result };
            res.status(200).json(jsonRes);
        });
    }   catch(err){
        res.status(500).send(err);
    }

My biggest question is whether I should use the pool.end() method and when I should, I’m learning Nodejs now for a college project so I don’t quite understand its workings.

1 answer

1


With the own documentation of the Node-postgres,the pool.end() drains the pool of all active customers, disconnects them and closes any internal timer in the pool. This is used in web applications when the web server is shut down intentionally or by some error handling.
You can use pool.end() to close all remaining customers, if you have finished with the pool. The purpose of the pool during its lifetime is to keep customers alive.
To turn off a pool, call pool.end (). This will await the return of all customers with check-out and will turn off all customers and pool timers. The pool will return errors when trying to check out a customer after you call pool.end (), where this explains the error that occurs in your code.
Try to rewrite your code for something similar to the one shown in the documentation.

    try{
     let pool = require ('./conexao');
 
     pool.query("SELECT * FROM pesquisaAlimentos('?')", (error, response) => {   
       console.log('Query terminada!');
       await pool.end();
       console.log('pool encerrada!'); 
   
       return res.rows;
     });
    }catch(err){
      throw(err);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.