다음 코드의 대해서 여러분들의 의견이 궁금합니다!

아래 코드는 제가 nestjs를 사용하여 서버로 login할 때 아이디와 비밀번호를 검증하는 부분입니다.

const user: User = await this.userRepository.findUserByEmail(email);

    if (!user) {
      throw new BadRequestException("아이디 혹은 비밀번호가 틀렸습니다.");
    }

    const compared: boolean = await bcrypt.compare(password, user.password);

    if (!compared) {
      throw new BadRequestException("아이디 혹은 비밀번호가 틀렸습니다.");
    }

되게 직관적이지만 조건문에서 조건이 일치할 때(즉 검증 로직에서 falsy한 값을 받을 때) 에러를 던지게 되는데 그 에러가 똑같은 모습이라 한번만 써도 될 것을 두 번 사용하여 보기가 껄끄럽게 된 것 같습니다. 만약 아이디와 비밀번호를 한번에 얻어오고 조건문을 사용하려면 user변수에 값이 있어야(즉 email로 유저를 찾게 되어야만) user.password 변수를 사용할 수 있어서 이러한 방법은 불가능해보입니다.

여러분들은 이런 코드가 어떻게 보이시나요?

아래와 같이 작성해보시는 건 어떨까요?

  • 타입스크립트 작성법을 몰라서 자바스크립트로 예시 작성해보았습니다. 죄송합니다.
    const user = await this.userRepository.findUserByEmail(email);
    const compared = user ? await bcrypt.compare(password, user.password) : null;

    if( !user || !compared ) throw new BadRequestException("Error message you want");
   
2개의 좋아요

&& 연산의 원리를 이용하면 이렇게 축약할 수도 있습니다.

const user = await this.userRepository.findUserByEmail(email);
const compared = user && await bcrypt.compare(password, user.password);

if (!compared) {
  throw new BadRequestException("아이디 혹은 비밀번호가 틀렸습니다.");
}

userfalsy하다면 compared는 false로 판정되고 뒤의 식을 실행하지 않습니다. 반대로 말하면 뒤의 식을 실행하려면 앞의 userfalsy하지 않아야 한다는 조건이 성립해야 한다는 뜻으로 받아들일 수 있습니다.

2개의 좋아요