프로젝트

트러블슈팅 1. 이메일검증

늘곰's 2023. 10. 7. 22:20

프로젝트를 시작하고 회원가입 로그인 기능을 구현하는 중 트러블 슈팅이 발생했다..
내가 원하는 것은 회원가입을 받을때 이메일 형식이 아닌 내용들은 가입이 되지 않도록 오류 처리를 하고 싶었는데 
DTO 에 IsEmail 을 넣었음에도 작동하지 않았다..

이걸 해결 하려면  schema.prisma 를 수정해서 .User 테이블안에 intro 와 nickname 을 넣어야하는데 
기존 스키마를 수정하지 않고 이것을 하려고하니 되지않았다.

한참을 찾다가  Pipe 설정이 안되어있다는것을 찾고... 파이프설정을해서 유효성검사를 하였다.

..   // 유효성 검사를 위한 ValidationPipe 설정
  app.useGlobalPipes(new ValidationPipe());

 

 

DTO

// src/users/dto/create-user.dto.ts

import { ApiProperty } from '@nestjs/swagger';
import { IsEmail, IsNotEmpty, IsString, MinLength } from 'class-validator';

export class CreateUserDto {
  @IsEmail() // IsEmail 데코레이터 추가
  @IsNotEmpty()
  @ApiProperty({
    description: 'email',
    example: 'abc123@naver.com',
  })
  email: string;

  @IsString()
  @IsNotEmpty()
  @MinLength(6)
  @ApiProperty({
    description: 'password',
    example: '123456',
  })
  password: string;

  @IsString()
  @IsNotEmpty()
  @ApiProperty({
    description: 'nickname',
    example: '닉네임',
  })
  nickname: string;

  @IsString()
  @IsNotEmpty()
  @ApiProperty({
    description: 'intro',
    example: '안녕하세요',
  })
  intro: string;

  @IsString()
  @IsNotEmpty()
  @ApiProperty({
    description: 'password',
    example: '123456',
  })
  confirm: string;
}

service

  async create({
    email,
    password,
    nickname,
    intro,
    confirm,
  }: IUsersServiceCreate): Promise<User> {
    const user = await this.findByEmail({ email });

    if (user) throw new ConflictException('이미 등록된 이메일 입니다.'); //에러 코드를 알아서 적어줌

    if (password !== confirm) {
      throw new BadRequestException(
        '비밀번호와 비밀번호 확인이 일치하지 않습니다.',
      );
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    // CreateUserDto 인스턴스 생성
    const createUserDto = new CreateUserDto();
    createUserDto.email = email;

    return this.prisma.user.create({
      data: {
        email: createUserDto.email,
        password: hashedPassword,
        UserDetail: {
          create: {
            nickname,
            intro,
          },
        },
      },
    });
  }

수정된 sevice

import {
  BadRequestException,
  ConflictException,
  Injectable,
} from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import * as bcrypt from 'bcrypt';
import { IUsersServiceFindByEmail } from './interfaces/users-service.interface';
import { User } from '@prisma/client';
import { CreateUserDto } from './dto/create-user.dto';

@Injectable()
export class UsersService {
  constructor(private prisma: PrismaService) {}

  findByEmail({ email }: IUsersServiceFindByEmail): Promise<User> {
    // 이코드는 여러번 재사용 될 수 있기 떄문에 따로 빼줌
    return this.prisma.user.findUnique({ where: { email } });
  }

  findOne(userId: number) {
    return this.prisma.user.findUnique({ where: { userId } });
  }

  async create(createUserDto: CreateUserDto): Promise<User> {
    const { email, password, nickname, intro, confirm } = createUserDto;

    const user = await this.findByEmail({ email });

    if (user) {
      throw new ConflictException('이미 등록된 이메일 입니다.');
    }

    if (password !== confirm) {
      throw new BadRequestException(
        '비밀번호와 비밀번호 확인이 일치하지 않습니다.',
      );
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    return this.prisma.user.create({
      data: {
        email,
        password: hashedPassword,
        UserDetail: {
          create: {
            nickname,
            intro,
          },
        },
      },
    });
  }