Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform multipart/form-data request body then use validationPipe

I'm trying to convert a formData requert from string to json object with transform and after that validate with the validationPipe (class-validator) but I get

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)

After try to debug I enter into my controller 3 times and the object is saved in the database but with no validation and inner transformJSONToObject 9 times ...

My main.ts

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();

My nestjs dto

export class CreateRestaurantDto {
  // to do, check the documentation from class-validator for array of objects
  @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[];
}

Here 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,
    };
 // just add a resturant to mongodb
    const createdRestaurant = await this.restaurantsService.addRestaurant(
      restaurant,
    );
    user.restaurants.push(createdRestaurant);
    user.save();
    return createdRestaurant;
  }
like image 686
anthony willis muñoz Avatar asked Mar 14 '26 06:03

anthony willis muñoz


1 Answers

I know it is too late now :) but maybe this can help someone

with the help of deep-parse-json, my solution is to create a ParseFormDataJsonPipe as below and put it right before ValidationPipe. you can pass an excepted list of form-data's properties in the constructor to keep some things purely such as image, binary, jsonArray...

import { PipeTransform, ArgumentMetadata } from '@nestjs/common';
import { deepParseJson } from 'deep-parse-json';
import * as _ from 'lodash';

type TParseFormDataJsonOptions = {
  except?: string[];
};

export class ParseFormDataJsonPipe implements PipeTransform {
  constructor(private options?: TParseFormDataJsonOptions) {}

  transform(value: any, _metadata: ArgumentMetadata) {
    const { except } = this.options;
    const serializedValue = value;
    const originProperties = {};
    if (except?.length) {
      _.merge(originProperties, _.pick(serializedValue, ...except));
    }
    const deserializedValue = deepParseJson(value);
    console.log(`deserializedValue`, deserializedValue);
    return { ...deserializedValue, ...originProperties };
  }
}

here is an example of the controller

  @Post()
  @ApiBearerAuth('admin')
  @ApiConsumes('multipart/form-data')
  @UseGuards(JwtAuthGuard, RoleGuard)
  @Roles(Role.Admin)
  @UseInterceptors(
    FileInterceptor('image', {
      limits: { fileSize: imgurConfig.fileSizeLimit },
    }),
  )
  async createProductByAdmin(
    @Body(
      new ParseFormDataJsonPipe({ except: ['image', 'categoryIds'] }),
      new ValidationPipe(),
    )
    createDto: CreateProductDto,
    @UploadedFile() image: Express.Multer.File,
  ) {
    console.log(`createDto`, createDto);
  }
like image 99
Lenam Avatar answered Mar 16 '26 00:03

Lenam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!