user8487780
user8487780

Reputation:

How to use transaction using knex.js

I have use knex to enter multiple recorods in database tables but i have not any response. my code is below:

  addApi : (data,CustomerId) => {
    knex.transaction(function(trx) {
      knex('books').transacting(trx).insert({name: 'Old Books'})
        .then(function(resp) {
          var id = resp[0];
          return someExternalMethod(id, trx);
        })
        .then(trx.commit)
        .catch(trx.rollback);
    })
    .then(function(resp) {
      console.log('Transaction complete.');
    })
    .catch(function(err) {
      console.error(err);
    });
  }

Upvotes: 2

Views: 6571

Answers (1)

GaryL
GaryL

Reputation: 1460

From your question, I am assuming that the transaction is successful although you are not getting a return value.

You are losing your return someExternalMethod(id, trx); response value. Instead you are getting the response value of the .then(trx.commit). And you are doing the same again in the console.log('Transaction complete.'); code section.

Try this (edited: code is now tested):

function testIt() {
    const knex  = require("knex")(dbcfg); // you will need your configuration

    function createBooksTable(table) {
        table.increments('id');
        table.string('name', 128);
    };

    function someExternalMethod(id, trx) {
        console.log("DBG02 .someExternalMethod Executed.");
        return [id];
    }

    function insertBooksRec() {
        return knex.transaction(function(trx) {
            knex('books').transacting(trx).insert({name: 'Old Books'})
            .then(function(resp) {
            var id = resp[0];
            return someExternalMethod(id, trx);
            })
            .then(function(extMethodReturn) {
            // return the value from the above .then
            console.log('DBG03 .extMethodReturn Returns:', extMethodReturn);
            return trx.commit()
                .then(function() { 
                    console.log('DBG04 .extMethodReturn Returns:', extMethodReturn);
                    return extMethodReturn; 
                });
            })
            .catch(trx.rollback)
            .then(function(resp) {
                console.log('DBG99 Insert Transaction complete. Returns:', resp);
                return resp; // if you want the value returned.
            })
            .catch(function(err) {
                console.error('DBG89 Insert Transaction ERROR:', err);
            });
        });
    };

    let tbl = knex.schema.createTableIfNotExists("books", createBooksTable)
    .then(function() {
        console.log('DBG01 BOOKS Table Creation complete:');
    })
    .catch(function(err) {
        console.error("DBG81 ERROR creating books table:", err);
    })
    .then(function() {
        return insertBooksRec()
    });

};
testIt();

Upvotes: 1

Related Questions