node.js – 取决于事务的Sequelize挂钩

我想在我的用户模型上在afterCreate上创建一个sequelize钩子.当我只创建一个没有事务的用户时,它工作得很好.但是如果我在事务中运行我的create语句,则在提交之前运行钩子.

用户模型钩子

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

钩功能

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

该事务在options.transaction中是可访问的.

在提交事务之后是否仍然运行钩子?

最佳答案 比赛有点晚,但是因为我在搜索答案时遇到了这个问题,这个问题可能对其他人有用.

如果在事务中创建用户,那么事务对象将在钩子回调的一个参数中传递(取决于版本). Link to docs.
以下内容直接从源链接复制:

// 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.

点赞