I am attempting to convert a formData request from string to a JSON object using transformation and then validate it with the validationPipe (class-validator). However, I encountered an issue:
Maximum call stack size exceeded
at cloneObject (E:\projectos\Gitlab\latineo\latineo-apirest\node_modules\mongoose\lib\utils.js:290:21)
at clone (E:\projectos\Gitlab\latineo\latineo-apirest\node_modules\mongoose\lib\utils.js:204:16)
Upon debugging, I noticed that my controller is being entered 3 times and the object is saved in the database without validation. The transformJSONToObject function is called 9 times...
This is my main.ts file:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({ transform: true }));
app.use(helmet());
app.enableCors();
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 4000, // limit each IP to 100 requests per windowMs
}),
);
app.use(compression());
app.use('/upload', express.static(join(__dirname, '..', 'upload')));
const options = new DocumentBuilder()
.setTitle('XXX')
.setDescription('XXX')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();
This is my nestjs DTO:
export class CreateRestaurantDto {
@IsString()
@IsNotEmpty()
@ApiModelProperty({ type: String })
@Length(3, 100)
readonly name: string;
@IsString()
@IsNotEmpty()
@ApiModelProperty({ type: String })
@Length(3, 500)
readonly description: string;
@Transform(transformJSONToObject, { toClassOnly: true })
@ValidateNested()
@ApiModelProperty({ type: [RestaurantsMenu] })
readonly menu: RestaurantsMenu[];
@Transform(transformJSONToObject, { toClassOnly: true })
@IsString({
each: true,
})
@IsNotEmpty({
each: true,
})
@Length(3, 50, { each: true })
@ApiModelProperty({ type: [String] })
readonly type: string[];
@Transform(transformJSONToObject, { toClassOnly: true })
@ValidateNested()
@ApiModelProperty({ type: [RestaurantsLocation] })
readonly location: RestaurantsLocation[];
}
This is my Controller:
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@UseInterceptors(FilesInterceptor('imageUrls'))
@ApiConsumes('multipart/form-data')
@ApiImplicitFile({
name: 'imageUrls',
required: true,
description: 'List of restaurants',
})
@Post()
async createRestaurant(
@Body() createRestaurantDto: CreateRestaurantDto,
@UploadedFiles() imageUrls,
@Req() request: any,
): Promise<RestaurantDocument> {
const userId = request.payload.userId;
const user = await this.usersService.findUserById(userId);
const mapUrls = imageUrls.map(element => {
return element.path;
});
const restaurant = {
...createRestaurantDto,
imagesUrls: mapUrls,
creator: user,
};
const createdRestaurant = await this.restaurantsService.addRestaurant(
restaurant,
);
user.restaurants.push(createdRestaurant);
user.save();
return createdRestaurant;
}