生命周期函数

有的时候,我们希望在存储之前干点什么,比如把用户的密码进行 Hash 一下。这个时候就需要用到生命周期函数了。

生命周期函数有哪些?有哪些种类?

支持的生命周期函数如下

  1. (1)
  2. beforeBulkCreate(instances, options)
  3. beforeBulkDestroy(options)
  4. beforeBulkUpdate(options)
  5. (2)
  6. beforeValidate(instance, options)
  7. (-)
  8. validate
  9. (3)
  10. afterValidate(instance, options)
  11. - or -
  12. validationFailed(instance, options, error)
  13. (4)
  14. beforeCreate(instance, options)
  15. beforeDestroy(instance, options)
  16. beforeUpdate(instance, options)
  17. beforeSave(instance, options)
  18. beforeUpsert(values, options)
  19. (-)
  20. create
  21. destroy
  22. update
  23. (5)
  24. afterCreate(instance, options)
  25. afterDestroy(instance, options)
  26. afterUpdate(instance, options)
  27. afterSave(instance, options)
  28. afterUpsert(created, options)
  29. (6)
  30. afterBulkCreate(instances, options)
  31. afterBulkDestroy(options)
  32. afterBulkUpdate(options)

这些周期函数分为全局的与模型级别的。

全局级别

  1. const sequelize = new Sequelize(..., {
  2. define: {
  3. hooks: {
  4. beforeCreate: () => {
  5. // Do stuff
  6. }
  7. }
  8. }
  9. });

模型级别

  1. const Project = sequelize.define('project', {}, {
  2. hooks: {
  3. beforeCreate: () => {
  4. // Do other stuff
  5. }
  6. }
  7. });

定义生命周期的三种方式

1.options

  1. const Project = sequelize.define('project', {}, {
  2. hooks: {
  3. beforeCreate: () => {
  4. // Do other stuff
  5. }
  6. }
  7. });
  8. const sequelize = new Sequelize(..., {
  9. define: {
  10. hooks: {
  11. beforeCreate: () => {
  12. // Do stuff
  13. }
  14. }
  15. }
  16. });

2.调用对应的方法

  1. sequelize.afterValidate('xxx', () => {....})
  2. User.afterValidate('myHookAfter', (user, options) => {
  3. user.username = 'Toni';
  4. });

3.调用 addHook

  1. sequelize.addHook('xxx', () => {....})
  2. User.addHook('afterValidate', 'notifyUsers', () => {....})

命名生命周期函数

取一个叫 notifyUsers 的名字

  1. User.afterValidate('myHookAfter', (user, options) => {
  2. user.username = 'Toni';
  3. });
  4. User.addHook('afterValidate', 'notifyUsers', () => {....})

移除生命周期函数

只有被命名了的生命周期函数才可移除

  1. Book.removeHook('afterValidate', 'notifyUsers');