Search code examples
typescriptnestjs

How do I configure a custom nestjs pipe?


I've got the most basic pipe that I would like to use on a method of a custom provider. The pipe looks as follows:

@Injectable()
export class DateTransformPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    console.log('Inside the DateTransformPipe pipe...');
    return value;
  }
}

And here is the class where I would like to use it:

@Injectable()
export class MyProvider {

    @UsePipes(new DateTransformPipe())
    private getDataFor(onDate: Date): string {
      console.log(onDate);
        return 'Some Stuff'
    }
}

The pipe is in a special directory src/helpers/pipes. The problem here is that the pipe's transform method is not called at all...I don't seem to figure out why.


Solution

  • Because pipes are only executed in nestjs process of request, so this function getDataFor is private, so I guess, you're executing it by some code in the MyProvider this is not how it works.

    Please read docs: https://docs.nestjs.com/pipes

    But keep in mind, that pipes are executed only in processing request by framework, not for every method that you might to have, Nest doesn't have this kind of power.

    So you can use that fe on methods bind to the controller path.

    fe:

    @Controller('cats')
    class CatController {
        @Post()
        @UsePipes(new DateTransformPipe())
        async create(@Body() createCatDto: CreateCatDto) {
        this.catsService.create(createCatDto);
        }
    }