Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJs validate array in request body

I'm trying insert validation into PUT request.

DTO's:

export class SettingUpdateDto implements ISettingUpdate {
    @IsInt()
    @IsPositive()
    id: number;

    @IsNotEmpty()
    @IsString()
    value: string;
}

export class SettingArrayUpdateDto {
    @Type(() => SettingUpdateDto)
    @ValidateNested({ each: true })
    items: SettingUpdateDto[];
}

Controller

@Put()
async updateItem(@Body() items: SettingArrayUpdateDto) {
    return await this.dataService.update(items);
}

Servise

async update(items: SettingArrayUpdateDto[]): Promise<Setting> {
    console.log("service data", items);
    return <Setting>{}; <SettingUpdateDto[]>items;
}

When i sent data, like this:

[
    {"id": -20, "value": {"name": "333"}},
    {"id": 21, "value": "2222222222222222"}
]

I received empty array. What am I doing wrong? Where is the mistake?

When i change settings in controller from SettingArrayUpdateDto to any, controller received original request data.

NestJs 6.10.14 version.

like image 947
sniffysko Avatar asked Apr 15 '26 16:04

sniffysko


1 Answers

To validate the array, create a dedicated class which contains a property that wraps the array, or use the ParseArrayPipe.

@Post()
createBulk(
  @Body(new ParseArrayPipe({ items: CreateUserDto }))
  createUserDtos: CreateUserDto[],
) {
  return 'This action adds new users';
}
like image 150
Eldari Avatar answered Apr 17 '26 12:04

Eldari



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!