Reputation: 121
I have NestJS API, which has a PATCH endpoint for modifying a resource. I use the class-validator
library for validating the payload. In the DTO, all fields are set to optional with the @IsOptional()
decorator. Because of that, if I send an empty payload, the validation goes through and then the update operation errors.
I am wondering if there is a simple way to have all fields set to optional as I do and at the same time make sure that at least one of them is not empty, so the object is not empty.
Thanks!
Upvotes: 3
Views: 5553
Reputation: 114
I don't know if it is possible using DTO. For that purpose I use Pipes. Like this:
Injectable()
export class ValidatePayloadExistsPipe implements PipeTransform {
transform(payload: any): any {
if (!Object.keys(payload).length) {
throw new BadRequestException('Payload should not be empty');
}
return payload;
}
}
Upvotes: 10