How to using one route with multiple dto on Nestjs?

Viewed 3535

Currently I am using NestJS to build restful api. I am having a ValidationPipe problem. it only works at controller method and not working with service methods.

I need to make choices for different DTO class (UserCreateDTO, StaffCreateDTO,...) for each ROLE (admin, staff, user) on a route.

1 Answers

Pipes only work on controllers, you cannot use them with services. But you can just use class-validator's validate method (together with class-transformer's plainToClass method) anywhere in your code instead:

const user = plainToClass(UserCreateDto, userRequestEntity);
const errors = await validate(user)
if (errors.length > 0) {
  throw this.createError(errors);
}

Also, you don't need to create multiple DTO classes for different roles. Just use class-validator groups:

Assign each property in your DTO to one or multiple groups (= roles):

@Min(12, {groups: ['admin', 'staff']})
age: number;
@Length(2, 20, {groups: ['admin']})
name: string;

Then pass your group (roles) to plainToClass and validate.

// Pass your roles as groups
const groups = ['admin'];

// Transform to class with groups
const entityClass = plainToClass(EntityDto, entity, { groups })

// Validate with groups
const errors = await validate(entityClass, { groups });
Related