ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Pipes
    Node.js/Nest 2023. 11. 13. 17:50

     


    Nest.js의 Pipes에 대해 정리하였습니다.



    < Pipes >

    A pipe is a class annotated with the @Injectable( ) decorator, which implements the PipeTransform interface.



    pipes operate on the  arguments  and have two typical use cases:

    • transformation: transform input data to the desired form (e.g., from string to integer)
    • validation: evaluate input data and if valid, simply pass it through unchanged; otherwise, throw an exception




    < Built-in Pipes >

    •  ValidationPipe 
    •  ParseIntPipe 
    •  ParseFloatPipe 
    •  ParseBoolPipe 
    •  ParseArrayPipe 
    •  ParseUUIDPipe 
    •  ParseEnumPipe 
    •  DefaultValuePipe 
    •  ParseFilePipe 


    Ex) ParseIntPipe
    - the pipe ensures that a method handler parameter is converted to a JavaScript integer (or throws an exception if the conversion fails).



    < Binding Pipes >

    To use a pipe, we need to bind an instance of the pipe class to the appropriate context


    Ex)

    @Get(':id')
    async findOne(@Param('id', ParseIntPipe) id: number) {
      return this.catsService.findOne(id);
    }

    This ensures that one of the following two conditions is true

    - either the parameter we receive in the findOne( ) method is a number

    - or an exception is thrown before the route handler is called.

    assume the route is called like:

    GET localhost:3000/abc
    {
      "statusCode": 400,
      "message": "Validation failed (numeric string is expected)",
      "error": "Bad Request"
    }




    < Custom Pipes >

    Every pipe must implement the transform( ) method to fulfill the PipeTransform interface contract. This method has two parameters:

    • value : the currently processed method argument (before it is received by the route handling method)
    • metadata : the currently processed method argument's metadata.

     

    Ex : validation.pipe.ts

    import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
    
    @Injectable()
    export class ValidationPipe implements PipeTransform {
      transform(value: any, metadata: ArgumentMetadata) {
        return value;
      }
    }

     

     

    The metadata object has these properties:

    export interface ArgumentMetadata {
      type: 'body' | 'query' | 'param' | 'custom';
      metatype?: Type<unknown>;
      data?: string;
    }
     type  Indicates whether the argument is a body @Body( ), query @Query( ), param @Param( ), or a custom parameter
     metatype  Provides the metatype of the argument, for example, String. Note: the value is undefined if you either omit a type declaration in the route handler method signature, or use vanilla JavaScript.
     data  The string passed to the decorator, for example @Body('string'). It's undefined if you leave the decorator parenthesis empty.

     

     


    < Schema based validation >

    Ex : Create Cat API

    @Post()
    async create(@Body() createCatDto: CreateCatDto) {
      this.catsService.create(createCatDto);
    }
    export class CreateCatDto {
      name: string;
      age: number;
      breed: string;
    }

     

     


    < Global-scoped Pipes >

    we can realize its full utility by setting it up as a global-scoped pipe so that it is applied to every route handler across the entire application.

    Global pipes are used across the whole application, for every controller and every route handler.

     

    main.ts

    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      app.useGlobalPipes(new ValidationPipe());
      await app.listen(3000);
    }
    bootstrap();

     

     

    app.module.ts

    import { Module } from '@nestjs/common';
    import { APP_PIPE } from '@nestjs/core';
    
    @Module({
      providers: [
        {
          provide: APP_PIPE,
          useClass: ValidationPipe,
        },
      ],
    })
    export class AppModule {}

     

     


    < Providing defaults >

     Parse*  pipes expect a parameter's value to be defined. They throw an exception upon receiving null or undefined values. To allow an endpoint to handle missing querystring parameter values, we have to provide a default value to be injected before the  Parse*  pipes operate on these values. The DefaultValuePipe serves that purpose.

     

    @Get()
    async findAll(
      @Query('activeOnly', new DefaultValuePipe(false), ParseBoolPipe) activeOnly: boolean,
      @Query('page', new DefaultValuePipe(0), ParseIntPipe) page: number,
    ) {
      return this.catsService.findAll({ activeOnly, page });
    }

     

     


    < Example >

    import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
    
    @Injectable()
    export class ParseIntPipe implements PipeTransform<string, number> {
      transform(value: string, metadata: ArgumentMetadata): number {
        const val = parseInt(value, 10);
        if (isNaN(val)) {
          throw new BadRequestException('Validation failed');
        }
        return val;
      }
    }
    @Get(':id')
    async findOne(@Param('id', new ParseIntPipe()) id) {
      return this.catsService.findOne(id);
    }

     

     


    Reference : https://docs.nestjs.com/pipes

     

    Documentation | NestJS - A progressive Node.js framework

    Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

    docs.nestjs.com

     

    'Node.js > Nest' 카테고리의 다른 글

    Custom Decorators  (0) 2023.12.08
    Guards  (0) 2023.11.21
    Exception Filters  (0) 2023.10.30
    Middlewares  (0) 2023.10.18
    Modules  (0) 2023.09.26

    댓글

Designed by Tistory.