Re-use method

Asked

Viewed 24 times

0

I made a query to search a user. It worked!

But I tried to make another appointment, he gave this message

Error: Cannot use a pool after calling end on the pool 

'Cause every time I make a connection, I close it later, and it seems like once it’s closed it doesn’t reopen anymore.

I’m using nodejs 10 with postgres

This is my method:

       return new Promise( (resolve, reject) => {
                const { pool, errorHandler } = deps
                const query = "SELECT * FROM public.usuario  WHERE cpf = $1"
                const queryData = [ cpf ]
                pool.connect()
                pool.query( query, queryData, (error, results) => {

                    if(error){
                        errorHandler(error, `Não foi possível encontrar usuário com cpf ${cpf}`, reject)
                        return false
                    }
                    if( results.rowCount > 0 ){
                        resolve({ usuario: results.rows })
                    }else{
                        resolve({msg: 'Usuário não encontrado'})
                    }

                })
                pool.end()
            })

Note that every time having access, I pass the method connect(), but it’s not working

And yet there’s this message:

Error: Called end on pool more than once

1 answer

0

I managed to solve by changing the code to

return new Promise( (resolve, reject) => {
                const { pool, errorHandler } = deps
                pool.connect((err, client, done) => {
                    if( err ){
                        errorHandler(err, `Problema ao conectar ao banco`, reject)
                        return false
                    }
                    const query = "SELECT * FROM public.usuario  WHERE cpf = $1"
                    const queryData = [ cpf ]
                    client.query( query, queryData, (error, results) => {
                        done()
                        if(error){
                            errorHandler(error, `Problema ao encontrar usuário com cpf ${cpf}`, reject)
                            return false
                        }
                        if( results.rowCount > 0 ){
                            resolve({ usuario: results.rows[0], msg: '', status: true })
                        }else{
                            resolve({msg: 'Usuário não encontrado', status: false})
                        }
                    } )
                })

According to the documentation

Browser other questions tagged

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