Postgress Transaction in NodeJs

1

I want to encapsulate my SQL execution in the Postgress database. My initial desire is to call a method to execute a specific query and another method to execute a multi-query transaction.

exports.executaSQL = function (select, listaParametros){
    client.connect(function (err) {
        if (err) throw err;
        client.query(select, listaParametros, function (err, result) {
            if (err) throw err;
            return result.rows;
            client.end(function (err) {
                if (err) throw err;
            });
        });
    });
};

/**
var objetoListaSelect = [];
objetoListaSelect.push({
    select : 'SELECT 1 WHERE ID=$1 AND ID=$2'
    params : [1, 6]
});
objetoListaSelect.push({
    select : 'SELECT 1 WHERE ID=$1 AND ID=$2'
    params : [1, 6]
});
**/
exports.executaTransacao = function (objetoListaSelect){

};

I would like the second function runTransaction to execute in the order it was added to the array, remembering the asynchronous execution of the queries, what would be a good solution?

Thank you in advance!

    
asked by anonymous 25.09.2016 / 21:21

1 answer

1

You can use Promises to do this. Creating a help function to make each request encapsulated in a Promise

function queryPromise(obj) {
    return new Promise(function(resolve, reject) {
        client.query(obj.select, obj.params, function(err, result) {
            if (err) reject(err);
            else resolve(result.rows);
        });
    });
}

Then you can use Promise.all() to wait for all the requests.

It would look like this:

var objetoListaSelect = [];
objetoListaSelect.push({
    select : 'SELECT 1 WHERE ID=$1 AND ID=$2'
    params : [1, 6]
});
objetoListaSelect.push({
    select : 'SELECT 1 WHERE ID=$1 AND ID=$2'
    params : [1, 6]
});

exports.executaTransacao = function(objetoListaSelect) {
    return new Promise(function(resolve, reject) {
        client.connect(function(err) {
            if (err) return reject(err);
            Promise.all(objetoListaSelect.map(queryPromise)).then(function(results) {
                client.end(function(err) {
                    if (err) reject(err);
                    else resolve(results);
                });
            });
        });
    });
};

And when you call this function you receive a promise. And to read the results would be something like:

const executaTransacao = require('./oTeuFicheiro').executaTransacao;

executaTransacao().then(function(resultados){
    console.log(resultados);
}).catch(function(erro){
    console.log(erro);
});
    
25.09.2016 / 21:31