Bcrypt with graphQL and nestJS

Bcrypt with graphQL and nestJS


0

In NestJS and GraphQL while using Bcrypt I had to use it with promise like below

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!' };
    }
  }

otherwise, if I was using it in a normal fashion like below

bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
    // result == true
});

it was throwing an error like
"Cannot return null for non-nullable field Query.getUser."

Does anyone know why this behavior?

1

  • It's because bcrypt.compare is async. You could also await the result. Also beware that you're allowing multiple users with the same email address so you may be matching the password with the wrong user.

    – Michel Floyd

    32 mins ago


Load 4 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *