ValidationPipe in provider

Viewed 139

NestJs:

How can I use validation like this:

@UsePipes(ValidationPipe)

in provider?

in file task.serive.ts tried to use @UsePipes(ValidationPipe) before method, but it doesn't appear

2 Answers

you can use like this,

export class LoginDto {
  // validation decorator to check for an email field!
  @IsEmail()
  readonly email: string;

  // validation decorators for password field!
  @IsNotEmpty()
  @IsString()
  readonly password: string;

  constructor(credentials: CredentialsInterface) {
    if (credentials) {
      this.email = credentials.email;
      this.password = credentials.password;
    }
  }
}

in your service,

import { validate } from 'class-validator';

const credentials = new LoginDto(req.body);
const errors = await validate(credentials);

   if (errors.length) {
      throw new BadRequestException({
        statusCode: HttpStatus.BAD_REQUEST,
        error: HttpErrors.BAD_REQUEST,
        message: errors,
      });
    }

You can't use Nest Enhancers from providers. They only bind to Controller,s Resovlers, and Gateways, as that is where the request enters and exists the server from. To get around this, at least class-validator, you can instantiate your own Validator class and run the validations.

Related