2017-02-04 103 views
1

這可能是基於觀點的。但我想獲得一些建議。使用sequelize和bcrypt異步

所以,我想要做的事情可以用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異步,我將不得不在另一個查詢中持久化加密的密碼。我的直覺告訴我,使用bcrypt async和sequelize可能會有更好的方式。

我的問題是,什麼是首選/更好的方法?或者我應該解決同步使用bcrypt?

回答

3

異步是去只是整理一下你的代碼了一下,在鉤使用回調

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

感謝您的回答方式。我不喜歡這種方法的主要原因是,會有兩個sql調用來堅持一個新用戶。 –

+0

只有一個sql調用,我們不調用保存在這裏,我們正在改變數據之前,sql調用fiered,你已經寫保存調用,這是不需要的 –

+0

hmm ...該記錄可能會持續在密碼散列之前生成,不是?因爲它是異步的。 –