Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

ví dụ dùng @UsePipes trong nestjs

  1. User

    ví dụ dùng @UsePipes trong nestjs

  2. Assistant

    Ví dụ:

    1. Tạo Pipe
    • Tạo file transform.pipe.ts với nội dung sau:
    import { PipeTransform, Injectable } from '@nestjs/common';
    
    @Injectable()
    export class TransformPipe implements PipeTransform {
      transform(value: any) {
        return (value || '').toString().toUpperCase();
      }
    }
    

    Pipe này được tạo để chuyển đổi giá trị của request thành chữ in hoa.

    1. Sử dụng Pipe:
    • Sử dụng Decorator @UsePipes để áp dụng Pipe trong Controller hoặc Method.

    • Ví dụ:

    import { Controller, Get, Post, Body, UsePipes } from '@nestjs/common';
    import { TransformPipe } from './transform.pipe';
    
    @Controller('example')
    export class ExampleController {
      
      @Get()
      @UsePipes(TransformPipe)
      async getExample() {
        return 'Example Response'
      }
    
      @Post()
      @UsePipes(TransformPipe)
      async postExample(@Body() body: any) {
        return `Your ${body} was transformed successfully!`
      }
    }
    

    Như vậy, Pipe TransformPipe đã được áp dụng trong cả hai request GET và POST của ExampleController. Khi request được gọi, giá trị của request sẽ được chuyển đổi thành chữ in hoa trước khi được xử lý.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.