声明 Hook

Hook 的参数通过引用传递. 这意味着你可以更改值,这将反映在insert / update语句中. Hook 可能包含异步动作 - 在这种情况下,Hook 函数应该返回一个 promise.

目前有三种以编程方式添加 hook 的方法:

  1. // 方法1 通过 .init() 方法
  2. class User extends Model {}
  3. User.init({
  4. username: DataTypes.STRING,
  5. mood: {
  6. type: DataTypes.ENUM,
  7. values: ['happy', 'sad', 'neutral']
  8. }
  9. }, {
  10. hooks: {
  11. beforeValidate: (user, options) => {
  12. user.mood = 'happy';
  13. },
  14. afterValidate: (user, options) => {
  15. user.username = 'Toni';
  16. }
  17. },
  18. sequelize
  19. });
  20. // 方法2 通过 .addHook() 方法
  21. User.addHook('beforeValidate', (user, options) => {
  22. user.mood = 'happy';
  23. });
  24. User.addHook('afterValidate', 'someCustomName', (user, options) => {
  25. return Promise.reject(new Error("I'm afraid I can't let you do that!"));
  26. });
  27. // 方法3 通过直接方法
  28. User.beforeCreate((user, options) => {
  29. return hashPassword(user.password).then(hashedPw => {
  30. user.password = hashedPw;
  31. });
  32. });
  33. User.afterValidate('myHookAfter', (user, options) => {
  34. user.username = 'Toni';
  35. });