Sök…


Introduktion

Vi kan behöva ändra attributen innan posten skapas. Mitt användningsfall var krypterande lösenord när användaren skapades.

Hooks doc är här http://docs.sequelizejs.com/sv/v3/docs/hooks/#instance-hooks . Det dokumenterar sättet att använda det med ett bibliotek / funktion som returnerar ett Promise . Men användningsfallet med ett återuppringning är inte tydligt dokumenterat.

Syntax

  • beforeCreate (exempel)
  • beforeCreate (instans, alternativ, fn)

Exempel på arbete med ett bibliotek som inte använder Promise

function cryptPassword(password, callback) {
  bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
    if (err)
      return callback(err);

    bcrypt.hash(password, salt, null, function(err, hash) {
      return callback(err, hash);
    });
  });
}

User.beforeCreate((user, options, cb) => {
  cryptPassword(user.password, (err, hash) => {
    if (err) return cb(err);

    user.password = hash;
    // invoking the finish callback is important!
    return cb(null, options);
  });    
});

Exempel på arbete med ett bibliotek som inte använder Promise

User.beforeCreate(function(user, options) {
  return hashPassword(user.password).then(function (hashedPw) {
  user.password = hashedPw;
  });
})


Modified text is an extract of the original Stack Overflow Documentation
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow