개발일지
[NestJS] 회원가입 구현 #1 - Pipe 적용 본문
회원가입 요구사항
- 이메일, 비밀번호, 이름을 입력받습니다.
- 유효성 검사
- 각 필드 빈칸 체크
- 이메일 중복 확인
- 비밀번호 일치 확인
Modeling
users.prisma를 생성한 뒤 Users 모델을 생성했습니다.
model Users {
id Int @id @default(autoincrement())
email String @unique
password String
nickname String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("users")
}
유효성 검사하기
입력받는 데이터에 대한 유효성 검증이 필요합니다. 이를 위해 class-validator
와 NestJS에서 제공하는 Pipe를 사용합니다.
DTO
먼저 회원 가입 시 입력받을 필드들을 정의한 SignUpUserDto를 생성합니다. class-validator에 내장된 데코레이터를 사용하여 규칙들을 정의해줍니다.
// common/dto/users.dto.ts
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class SignUpUserDto {
@IsEmail()
@IsNotEmpty()
email: string;
@IsString()
@IsNotEmpty()
nickname: string;
@IsNotEmpty()
password: string;
@IsNotEmpty()
checkPassword: string;
}
// users.controller
@Post('sign-up')
async signUp(@Body() data: SignUpUserDto): Promise<SignUp> {
return await this.usersService.signUp(data);
}
Pipe
Pipe는 NestJS에서 제공하는 미들웨어 중 하나로 보통 1. data transformation 2. data validation 목적으로 사용됩니다. 위에서 정의된 객체는 ValidationPipe
를 거치게 됩니다. ValidationPipe는 NestJS 내장 패키지 @nestjs/common
에서 제공됩니다.
모든 라우터 핸들러에서 적용될 수 있도록 전역 설정해줍니다.
// main.ts
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
...
}
bootstrap();
'NestJS, Node.js > #01 Project - 투표 커뮤니티' 카테고리의 다른 글
[NestJS] 로그인 구현 #1 - 유효성 검증 (0) | 2022.10.27 |
---|---|
[NestJS] 회원가입 구현 #2 - 유효성 검증 (0) | 2022.10.27 |
[NestJS] 예외 처리와 exception filter (0) | 2022.10.27 |
[NestJS] Interceptor 적용하기 (0) | 2022.10.27 |
[NestJS] 프로젝트 세팅하기 (0) | 2022.10.27 |