sequelize.js
beforeCreate 후크의 속성 수정
수색…
소개
레코드가 작성되기 전에 속성을 수정해야 할 수도 있습니다. 사용자가 생성되면 암호를 암호화하는 유스 케이스가있었습니다.
후크 문서는 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