본문 바로가기
NestJS

[NestJS] createDto.toEntity() is not a function 에러

by Sondho 2024. 3. 19.

사전 배경

// createDto
export class CreateUserDto {
  toEntity() {
    return new User();
  }
}

-----
// entity
export calss userEntity {
  constructor() {}
}

-----
// controller
@Post()
create(@Body() createUserDto: CreateUserDto) {
  return this.usersService.signUp(createUserDto);
}

 

문제 발생

  • Controller에서 @Body를 통해 받은 CreateUserDto를 Entity로 변환하기 위해 createUserDto.toEntity()를 호출하면 예외 발생

[ExceptionHandler] createUserDto.toEntity is not a function

 

원인 파악

  • 디버깅 해보니 Controller에서 @Body를 통해 받은 CreateUserDto에는 toEntity가 존재하지 않는다.
  • 네트워크를 통해 들어오는 페이로드는 일반 javascript 객체이다. CreateUserDto로 자동으로 변환이 되지 않는다. 참고

디버깅 해보니 toEntity()가 존재하지 않는다.

 

해결 방안 탐색

  • ValidationPipe는 payload를 DTO 클래스에 따라 입력되는 객체로 자동 변환할 수 있다. 자동 변환을 가능하게 하려면 transform: true로 설정해야 한다. 참고

 

문제 해결

  • 방법 1. controller.ts에서 메소드에서 처리
// controller.ts
@Post()
@UsePipes(new ValidationPipe({ transform: true })) // 추가된 코드
create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
}

 

  • 방법 2. main.ts에서 전역적으로 처리
// main.ts
app.useGlobalPipes(
  new ValidationPipe({
    transform: true,
  }),
);

 

결과

코드 수정 후

참고 자료

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

댓글