在 NestJS 和 GraphQL 中使用 Bcrypt 时,我必须像下面这样使用 Promise
async getUser(email: String, password: String) {
let user: User[] | User | null = await this.userModel.find({ email });
user = user.length && user[0];
if (user) {
return bcrypt
.compare(password, user.password)
.then((res: any) => {
if (res) {
return { result: true, message: 'Logged in successfully.'};
} else return { result: false, message: 'Incorrect Password.' };
})
.catch((err) => {
return { result: false, message: err.message };
});
} else {
return { result: false, message: 'User not found. Try Sign-up!' };
}
}
否则,如果我像下面这样以正常方式使用它
bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
// result == true
});
它抛出了一个错误,比如
"Cannot return null for non-nullable field Query.getUser."
有谁知道为什么会出现这种行为?
您可以轻松使用compareSync进行同步
// Load hash from your password DB.
bcrypt.compareSync(myPlaintextPassword, hash); // true
bcrypt.compareSync(someOtherPlaintextPassword, hash); // false