サーチ…


前書き

レコードが作成される前に属性を変更する必要があるかもしれません。私のユースケースは、ユーザーの作成時にパスワードを暗号化することでした。

フックのdocはhttp://docs.sequelizejs.com/en/v3/docs/hooks/#instance-hooksです。これは、 Promiseを返すライブラリ/関数でそれを使用する方法を文書化しています。しかし、コールバックを持つユースケースは明確に文書化されていません。

構文

  • beforeCreate(インスタンス)
  • beforeCreate(インスタンス、オプション、fn)

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);
  });    
});

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
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow