Pipes

Server Enviroment
Client Enviroment

Overview

Pipes can be used to transform the input data before passing it to the handler method.

Creating a Pipe

Pipes are classes that implement the Pipe interface. The Pipe interface has a transform method that returns the transformed data.

@Injectable()
export class MangoColorPipe implements Pipe<MyMangoData> {
    public transform(data) {
        return data.isRipe ? 'yellow' : 'green';
    }
}
typescript

Using a Pipe

Pipes can be used at the module, controller, or handler level. To use a pipe at the controller level, use the @UsePipes decorator.

NOTE
  • When you specify a pipe as a class reference, it is instantiated as a singleton by the dependency injection container. This means that the same instance is used for all requests. If you want to use a new instance for each request, you can specify an instance of the pipe instead of a class reference.
  • If you're using class references, don't forget to add the @Injectable decorator and add the guard to the providers array in the module.
+
+
@UsePipes(MangoColorPipe) 
@Controller()
export class DeliciousMangoController {
    @UsePipes(MangoColorPipe) 
    @On('eat')
    public onEat(@Param('mango', ColorPipe) color: 'green' | 'yellow') {
        console.log(`I am eating a ${color} mango!`);
    }
}

@Module({
    controllers: [DeliciousMangoController],
    providers: [MangoColorPipe],
})
export class DeliciousMangoModule {}
typescript

Also, instead of providing a class reference, you can provide an instance of the pipe. However, dependency injection will not work for the pipe instance.

+
@UsePipes(new MangoColorPipe()) 
@Module({
    controllers: [DeliciousMangoController],
})
export class DeliciousMangoModule {}
typescript
Last update at: 2024/06/18 19:03:08