i have app with NestJs with server and client separately, in server side I use ValidationPipe
and use decorators on DTO classes, for example
export class SearchDto {
@IsOptional()
readonly offset?: string;
@IsString()
readonly value: string;
@IsNumber()
readonly limit: number;
}
And all works OK, but on the client-side I can't use classes with decorators (its strict rule) and I simply need to use it like type
, - const search: SearchDto = await...
How class-validator
(class-transformer
) works when there is no ValidationPipe
over it? Is it wrapped it as in server side or it fully ignored? is it calls __decorate
and put it inside js bundle?
Otherwise I need to write interfaces like this
export class SearchDto implements ISearchDto {
@IsOptional()
readonly offset?: string;
@IsString()
readonly value: string;
@IsNumber()
readonly limit: number;
}
export interface ISearchDto {
offset?: string;
value: string;
limit: number;
}
let decorated: SearchDto;
let nonDecorated: ISearchDto;
Thank's for help
If you aren't allowed to use classes with decorators, you may want to look into using class-validator with schemas so that decorators are not necessary.
Class-validator works by setting metadata about fields via the decorators it uses, and can only do so much on type alone. The library then reads that metadata and checks it against the current type of the object/field and determines if its conditions are satisfied. The library is self contained so it doesn't need to go to a server or anything. If you look at the source code for the ValidationPipe
, you can see that Nest is just transforming the object with class-transformer
(also known as deserializing) to make the JSON object a JavaScript Class, then runs that class through class-validator
, checks the results, and returns, either the instance of the object ( if transform: true
is set in the options), or the original payload after it's been validated.
The metadata defined by these decorators though can be mimicked through a schema file as described in the first link above.