Home > Back-end >  why changed function in sequelize.js is not working in afterValidate hook?
why changed function in sequelize.js is not working in afterValidate hook?

Time:01-16

hooks: {
  afterValidate: async function (user, next) {
   if (!user.changed("password")) {
     next()
   };
   const salt = await bcrypt.genSalt(10);
   user.password = await bcrypt.hash(user.password, salt);
 }
},

When i try to run this code it throws an error saying next is not a function. And if i don't use changed function whenever i try to reset my password it rehash it. So what is wrong in my code and what do you suggest about the solution. Thank u. I just want to do it like this

CodePudding user response:

i had two problems - 1: why my reset password was not working properly , 2: why it throws an error about next is not a function. So, here i found the solutions after some debugging and some help from the comment of Mr.Anatoly. solution of 1 : I need to use beforeSave hook for the reset password to work and solution of 2 : I need to call empty return to go to the next hook

Complete solution of the problem looks like this :

beforeSave: async function (user)  {
                if (!user.changed("password")) { 
                    return;
                }
                else {
                    const salt = await bcrypt.genSalt(10);
                    user.password = await bcrypt.hash(user.password, salt);
                }

CodePudding user response:

Hooks do not have next as a function (like in Express.js routes), the second parameter is options that look like this:

  /**
   * An array of strings. All properties that are in this array will not be validated
   */
  skip?: string[];
  /**
   * An array of strings. Only the properties that are in this array will be validated
   */
  fields?: string[];

To go to the next validation hook you just need to call return to exit from the current hook.

hooks: {
  afterValidate: async function (user, next) {
   if (!user.changed("password")) {
     return;
   };
   const salt = await bcrypt.genSalt(10);
   user.password = await bcrypt.hash(user.password, salt);
 }
},
  •  Tags:  
  • Related