dmitriy-nz / nestjs-form-data

NestJS middleware for handling multipart/form-data, which is primarily used for uploading files.
https://www.npmjs.com/package/nestjs-form-data
MIT License
118 stars 23 forks source link

Transform and IsInt for arrays are not working #9

Closed unkindypie closed 3 years ago

unkindypie commented 3 years ago

DTO:

export class RegisterAccountDto {
   ...

  @ApiProperty({ type: [Number] })
  @Transform(({ value }) => {
    return Number(value);
  })
  @IsInt({ each: true })
  expertiseKeywordIds: number[];

}

Payload:

image

Route handler gets this value:

expertiseKeywordIds: 1

Without any decorators everything works although I need to parse and validate array manually. IsInt without Transform have the same bug.

dmitriy-nz commented 3 years ago

Hi, the problem is that you transform the array of strings into a number. @Transform decorator is not called for every value of the array, but only for the entire array. image

dmitriy-nz commented 3 years ago

Please read the documentation for class-transformer You can use this decorator to convert an array of strings to an array of numbers

//ToNumber.ts
export function toNumber(value: any) {
  const res: number = +value;
  return (isNaN(res)) ? null : res;
}

export function ToNumber(): (target: any, key: string) => void {
  return Transform((params: TransformFnParams) => toNumber(params.value));
}

//ToArrayNumber.ts
export function toArrayNumber(v: any[]): number[] {
  return (Array.isArray(v))
    ? v.map(v => toNumber(v))
    : null;
}

export function ToArrayNumber(): (target: any, key: string) => void {
  return Transform((params: TransformFnParams) => toArrayNumber(params.value));
}
unkindypie commented 3 years ago

My bad, thank you for the explanation.