DTO이 필요한 부분
회원가입을 할 때 유저가 email, name, password를 입력한다고 가정하자. 프론트에서 백엔드의 signUp POST API로 보낸 Body 값의 예시를 표현하면 아래와 같다. 그런데 이 데이터 양식이 적절한지를 통제하기 위해 DTO를 사용하면 좋다.
{
"email" : "john@email.com",
"name" : "John",
"password" : "1234"
}
DTO 생성
cats 모듈 디렉토리 내 dto 폴더를 만들어서 request dto를 생성해주었다.
// src/cats/dto/cats.requrest.dto.ts
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class CatRequestDto {
@IsEmail()
@IsNotEmpty()
email: string;
@IsString()
@IsNotEmpty()
password: string;
@IsString()
@IsNotEmpty()
name: string;
}
DTO 적용
...
@Controller('cats')
@UseInterceptors(SuccessInterceptor)
@UseFilters(HttpExceptionFilter)
export class CatsController {
constructor(private readonly catsService: CatsService) {}
@Get()
getCurrentCat() {
return 'current cat';
}
@Post()
async signUp(@Body() body: CatRequestDto) { // body값에 DTO 적용
return body;
}
...
결과
body값이 조건에 맞을 때는 정상 응답한다.
DTO 조건에 맞지 않아(email 프로퍼티 누락) 400 에러를로 응답한다.
'Research > Nest.js' 카테고리의 다른 글
nestjs_swagger 적용 및 dto OOP적 리팩토링 (0) | 2023.04.05 |
---|---|
nestjs_signup api 구현 + virtual 필드로 민감정보는 숨기기 (0) | 2023.04.05 |
nestjs_mongoose 스키마 설계 후 class-validator 적용 (0) | 2023.04.05 |
nestjs_배포 환경에 따른 mongoDB 로깅 설정 (0) | 2023.04.05 |
nestjs_환경변수 설정 +mongodb 연동 (0) | 2023.04.05 |
댓글