Declaring Hooks

Arguments to hooks are passed by reference. This means, that you can change the values, and this will be reflected in the insert / update statement. A hook may contain async actions - in this case the hook function should return a promise.

There are currently three ways to programmatically add hooks:

  1. // Method 1 via the .init() method
  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. // Method 2 via the .addHook() method
  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. // Method 3 via the direct method
  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. });