2
votes

I'm trying to get the nest validator working as in the example in the 'pipes' document (https://docs.nestjs.com/pipes) section "Object schema validation" . I'm trying the example using Joi which works except the passing of the schema from the controller to the validate service.

import * as Joi from 'joi';
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException 
} from '@nestjs/common';

@Injectable()
export class JoiValidationPipe implements PipeTransform {
  constructor(private readonly schema) {}

  transform(value: any, metadata: ArgumentMetadata) {
   const { error } = Joi.validate(value, this.schema);
     if (error) {
       throw new BadRequestException('Validation failed');
   }
   return value;
  }
}

The compiler complains:

Nest can't resolve dependencies of the JoiValidationPipe (?). Please make sure that the argument at index [0] is available in the current context.

In the controller

@Post()
@UsePipes(new JoiValidationPipe(createCatSchema))
async create(@Body() createCatDto: CreateCatDto) {
  this.catsService.create(createCatDto);
}

there the compiler complains one argument given zero expected.

It looks like a declaration issue but I don't really know. Why doesn't this work and how should I pass the schema to the service?

1

1 Answers

2
votes

As you stated yourself JoiValidationPipe must not be declared as a provider in any module.


I can only reproduce the error with this code (not passing a schema):

@UsePipes(JoiValidationPipe)
async create(@Body() createCatDto: CreateCatDto) {
  this.catsService.create(createCatDto);
}

Make sure you do not have this anywhere in your code.

This works for me:

@UsePipes(new JoiValidationPipe(Joi.object().keys({ username: Joi.string().min(3) })))
async create(@Body() createCatDto: CreateCatDto) {
  this.catsService.create(createCatDto);
}