10

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.

2 Answers 2

27

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';
}
Sign up to request clarification or add additional context in comments.

2 Comments

ParseArrayPipe is from Nest.js v7, the author was looking for a solution in v6
Does it work for you? I'm having problems in my project running latest version of NestJS
1

With the definition of the SettingArrayUpdateDto class, you need to send in a payload that matches it completely. That means your payload need to be

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

Because the SettingArrayUpdateDto has the items property which is of type SettingUpdateDto[].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.