'Knex event on transaction success

I have a function that takes a transaction object as an argument. Can this function subscribe to an event that fires when the transaction is commited?

function createUser (data, trx) {
  trx.on('success', .. )
  return User.create(data, { transacting: trx })
}

I don't see anything like that in the source, if not inner/outer transaction can be used somehow. https://github.com/tgriesser/knex/blob/master/src/transaction.js



Solution 1:[1]

I never found better solution. But transaction is event emmiter so you can override default knex functions to emit your custom event.

  • Override commit to fire event.

      knex = require('knex')({...});
      const _transaction = knex.transaction;
      knex.transaction = (cb) => {
          return _transaction(trx => {
              const _commit = trx.commit;
              trx.commit =async  (conn, value) => {
                  const out = await _commit(conn, value);
                  trx.emit('commit');
                  return out;
              }
    
              return cb(trx);
          })
      };
    
  • Listen to commit event anywhere in code

     knex.transaction(async trx => {
          trx.on('commit', async () => {
              // fired after commit is done
          });
    
          await trx.select().from('users').update({...});
      })
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user3934919