Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize hook depending on transaction

I want to create a sequelize hook on afterCreate on my user model. it work great when i just create a user without a transaction. but if i run my create statement in a transaction the hook is run before the commit.

user Model hooks

hooks: {
    afterCreate: userModule.NewUserHook,
    afterBulkCreate: userModule.NewUserHook
}

Hook function

NewUserHook: function NewUserHook(user, options){
    console.log('Inside hook');
}

The transaction is accesssible in options.transaction.

Is there anyway to run the hook after the transaction is commited?

like image 889
Jacob Avatar asked Jan 26 '16 13:01

Jacob


People also ask

How do you use Sequelize hooks?

Hooks (also known as lifecycle events), are functions which are called before and after calls in sequelize are executed. For example, if you want to always set a value on a model before saving it, you can add a beforeUpdate hook. Note: You can't use hooks with instances. Hooks are used with models.

What is individual hooks Sequelize?

Sequelize hooks are lifecycle events that get executed during a specific period of time. These hooks are JavaScript functions that run before or after an operation has been completed by Sequelize. Let's see an easy example that demonstrates one of the hooks in action.

How do you define a model in Sequelize?

Models can be defined in two equivalent ways in Sequelize: Calling sequelize.define(modelName, attributes, options) Extending Model and calling init(attributes, options)


1 Answers

A bit late to the game but since I came across this question while searching for answers, this one may be useful for others.

If you create the user inside a transaction then the transaction object will be passed in one of the arguments of the hook callback (depending on version). Link to docs. The following is copied directly from the source link:

// Here we use the promise-style of async hooks rather than
// the callback.
User.hook('afterCreate', (user, options) => {
  // 'transaction' will be available in options.transaction

  // This operation will be part of the same transaction as the
  // original User.create call.
  return User.update({
    mood: 'sad'
  }, {
    where: {
      id: user.id
    },
    transaction: options.transaction
  });
});


sequelize.transaction(transaction => {
  User.create({
    username: 'someguy',
    mood: 'happy',
    transaction
  });

If we had not included the transaction option in our call to User.update in the preceding code, no change would have occurred, since our newly created user does not exist in the database until the pending transaction has been committed.

like image 81
AlexanderF Avatar answered Sep 20 '22 11:09

AlexanderF