A
A
Alexander2021-09-23 14:05:26
Node.js
Alexander, 2021-09-23 14:05:26

How to refactor this code?

How can you prevent code duplication with an error?
I will be grateful for help

async login(email: string, password: string) {
    const user = await User.findOne({ where: { email } })

    if (!user) {
      throw ApiError.BadRequest('Your email or password was entered incorrectly.')
    }
    const isPassEquals = await bcrypt.compare(password, user.password)
    if (!isPassEquals) {
      throw ApiError.BadRequest('Your email or password was entered incorrectly.')
    }
    const userDto = new UserDto(user)
    const tokens = tokenService.generateTokens(userDto.id, userDto.email)
    await tokenService.saveToken(userDto.id, tokens.refreshToken)
    return { ...tokens, user: userDto }
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-09-23
@axrising

For example, you can move the validation code into a separate function:

async findUserByEmailAndPassword(email: string, password: string): User {
    const user = await User.findOne({ where: {email} });
    if(user) {
        const passwordValid = await bcrypt.compare(password, user.password);
        if(passwordValid)
            return user;
    }
    return null;
}

And then in the place of use:
const user = await findUserByEmailAndPassword(email, password);
if(user === null)
  throw ApiError.BadRequest('Your email or password was entered incorrectly.');

Well, or you can await bcrypt.compare(password, user.password)drag it into if, but I don’t really like this option.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question