Reputation: 429
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();
}
}
Upvotes: 0
Views: 1172
Reputation: 2598
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
Upvotes: 1