Petite note rapide décrivant comment /bien/ valider les DTO entrantes pour les endpoints NestJS. En effet, il est facile d’oublier la bonne annotation et d’accepter des DTO non-valides.
Types primitifs
@IsNumber() pace: number;
@IsString() timezone: string;
@IsBoolean() isActive: boolean;
Attributs facultatifs
@IsBoolean() @IsOptional() isActive?: boolean;
Tableaux
@IsArray() @ValidateNested({ each: true }) @Type(() => MyItemType) myArray: Array<MyItemType>;
Objets
@IsNotEmptyObject() @ValidateNested() @Type(() => MyObjectType) myObject: MyObjectType;
Notes:
– @IsNotEmptyObject() is very much required: if absent, the absence of the whole ‘myObject’ in the DTO will be considered valid
– { each: true } in @ValidateNested is not adequate for Objects
