I want to use validation groups in my DTO and use them in my controller. Does anyone know how you can use/pass validation groups to the controller or have the request.user automatically pass it to the controller?
create-user.dto.ts
export class CreateUserDto {
@IsNotEmpty({
groups: ["admin"],
})
role: string;
@IsNotEmpty()
@IsEmail()
email: string;
@IsNotEmpty()
password: string;
}
users.controller.ts
@Controller('users')
@UseGuards(JwtAuthGuard)
@UseInterceptors(ClassSerializerInterceptor)
export class UsersController {
constructor(
private readonly usersService: UsersService,
) {}
@Post()
async create(@Body() createUserDto: CreateUserDto): Promise<User> {
const result = await this.usersService.create(createUserDto);
return result;
}
}
@IsNotEmpty and @IsEmail decorators are coming from the class-validator library, so you should use ValidationPipe
Nest JS docs about validation: https://docs.nestjs.com/techniques/validation
Updated users.controller.ts:
@Controller('users')
@UseGuards(JwtAuthGuard)
export class UsersController {
constructor(
private readonly usersService: UsersService,
) {}
@Post()
@UsePipes(new ValidationPipe({ groups: ["admin"] }))
async create(@Body() createUserDto: CreateUserDto): Promise<User> {
const result = await this.usersService.create(createUserDto);
return result;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With