Pipes are only suitable for use in controllers and cannot be used with services. However, you can utilize the validate
method from class-validator (alongside the plainToClass
method from class-transformer) anywhere within your code:
const user = plainToClass(UserCreateDto, userRequestEntity);
const errors = await validate(user)
if (errors.length > 0) {
throw this.createError(errors);
}
Furthermore, there is no requirement to create distinct DTO classes for various roles. Simply leverage class-validator
groups:
Assign each property in your DTO to one or more groups (= roles):
@Min(12, {groups: ['admin', 'staff']})
age: number;
@Length(2, 20, {groups: ['admin']})
name: string;
Then provide your group (roles) to plainToClass
and validate
.
// Provide your roles as groups
const groups = ['admin'];
// Convert to class with groups
const entityClass = plainToClass(EntityDto, entity, { groups })
// Validate with groups
const errors = await validate(entityClass, { groups });