0

Nestjs documentation advises to use classes instead of interfaces for the DTO's because they are preserved as real entities in the compiled JavaScript but in reality the payload classes are not properly instantiated (with new()), they are Objects with the same shape as the class. The below example does not work. Is there a way to get a properly instantiated runtime CatDto class in the example ?

class CatsDto {
  constructor(private name: string) {}
  public greet() {
    return `${this.name} say miaouw`;
  }
}

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Post()
  getGreeting(@Body() cat: CatsDto): string {
    return cat.greet();
  }
}
Stefaan Vandevelde
  • 339
  • 1
  • 4
  • 7
  • Is [class-transformer](https://github.com/typestack/class-transformer) installed in your `package.json` ? What is the result of `cat.greet()` ? – Marco Mar 09 '21 at 08:02

1 Answers1

1

You need to use the ClassTransformer pipe to transform objects that are passed as arguments of your controller actions: https://docs.nestjs.com/techniques/validation#transform-payload-objects

Terenoth
  • 2,458
  • 1
  • 14
  • 21