gpt4 book ai didi

javascript - 将 Sequelize 与 bcrypt async 一起使用

转载 作者:行者123 更新时间:2023-11-30 11:42:40 26 4
gpt4 key购买 nike

这可能是基于意见的。但我想得到一些建议。

所以,我想做的可以按照this thread中提到的方式完成.但是this thread很好地说明了我为什么要使用异步。

这是我目前所拥有的,并且有效。

User.create({email: req.body.email, password: req.body.password}).catch(function(err){
console.log(err);
});

User.beforeCreate(function(user) {
const password = user.password;
user.password = '';
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if(err) console.error(err);
bcrypt.hash(user.password, salt, null, function(err, hash) {
if(err) console.error(err);
user.password = hash;
user.save();
});
});
});

由于我使用的是 bcrypt async,因此我必须在另一个查询中保留加密密码。我的直觉告诉我,使用带有 sequelize 的 bcrypt async 可能是更好的方法。

我的问题是,首选/更好的方法是什么?或者我应该只接受同步使用 bcrypt 吗?

最佳答案

异步是整理代码并在钩子(Hook)中使用回调的方式

function cryptPassword(password, callback) {
bcrypt.genSalt(10, function(err, salt) { // Encrypt password using bycrpt module
if (err)
return callback(err);

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

User.beforeCreate(function(model, options, cb) {
debug('Info: ' + 'Storing the password');
cryptPassword(user.password, function(err, hash) {
if (err) return cb(err);
debug('Info: ' + 'getting ' + hash);

user.password = hash;
return cb(null, options);
});
});

关于javascript - 将 Sequelize 与 bcrypt async 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42037278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com