sequelize.js
Modifier les attributs dans le hook beforeCreate
Recherche…
Introduction
Nous devrons peut-être modifier les attributs avant que l'enregistrement ne soit créé. Mon cas d'utilisation était le cryptage du mot de passe lors de la création de l'utilisateur.
Hooks doc est ici http://docs.sequelizejs.com/en/v3/docs/hooks/#instance-hooks . Il documente la façon de l'utiliser avec une bibliothèque / fonction qui renvoie une Promise . Mais le cas d'utilisation avec un rappel n'est pas clairement documenté.
Syntaxe
- beforeCreate (instance)
- beforeCreate (instance, options, fn)
Exemple d'utilisation d'une bibliothèque qui n'utilise pas 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);
});
});
Exemple d'utilisation d'une bibliothèque qui n'utilise pas 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
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow