Learn NestJS · 4/14

Pipes: Validation and Transformation

3 min read

管道:验证与转换 (Pipes: Validation and Transformation) 🏭

欢迎来到 NestJS 指南的又一章节!今天,我们将探讨一个非常酷且极其有用的概念:管道 (Pipes)。

想象一下,你正在经营一个高科技装配线工厂(你的 NestJS 应用)。原材料(来自客户端请求的数据)不断地进入工厂。你的工作是确保这些原材料在进入主要装配阶段(你的业务逻辑/服务)之前,不仅是正确的类型,而且符合质量标准。如果送来的是塑料而不是金属,或者零件尺寸不对,整个生产线就可能停顿下来!

这就是管道的作用。它们是你生产线上的自动化质量控制和加工站。

1. 管道简介:格式化与检查数据 🕵️‍♀️

问题 🤔

客户端发送的数据本质上是“愚蠢的”。例如,当用户通过 URL(如 /users/123)请求数据时,123 最初是一个字符串 "123",而不是一个数字。同样,当用户提交一个注册表单时,他们可能会发送一个格式不正确的电子邮件,或者密码太短。在每个控制器中手动检查这些问题会使你的代码变得混乱、重复且难以维护。

解决方案 💡

NestJS 中的管道是一个带有 @Injectable() 装饰器的类,它实现了 PipeTransform 接口。管道位于请求和你的路由处理器之间。在你的控制器方法被调用之前,管道会拦截并处理其参数。

管道有两个核心使命:

  1. 转换 (Transformation): 将输入数据转换为所需的格式(例如,将字符串 "123" 转换为数字 123)。
  2. 验证 (Validation): 评估输入数据,如果数据有效,则原样通过;如果无效,则抛出一个异常。

这种机制让你的控制器保持干净,专注于其核心职责,同时将验证和转换逻辑集中到可重用的模块中。


2. 使用内置管道 (ParseIntPipe, ParseUUIDPipe) 🔧

NestJS 非常友好,为我们提供了一些开箱即用的内置管道,可以处理最常见的任务。

ParseIntPipe: 字符串到数字的魔术师

问题: 路由参数,如 findOne(@Param('id') id: string) 中的 id,总是以字符串形式出现。如果你的服务层期望一个数字类型的 ID,你就必须手动转换它,例如使用 parseInt()。

解决方案: ParseIntPipe 会自动为你完成这项工作。

示例:

typescript
import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get(':id')
  async findOne(@Param('id', ParseIntPipe) id: number) {
    // 此时,'id' 已经是一个数字了!
    // 不再需要 const numericId = parseInt(id, 10);
    return this.usersService.findOne(id);
  }
}

如果传入的参数无法转换为数字(例如 users/abc),ParseIntPipe 会自动抛出一个 BadRequestException,向客户端发送一个清晰的 400 错误响应。这真是太棒了!

ParseUUIDPipe: UUID 格式的守护者

问题: 当你使用 UUIDs作为实体的主键时,你需要确保传入的 ID 是一个有效的 UUID。手动编写正则表达式来验证它既繁琐又容易出错。

解决方案: ParseUUIDPipe 保证参数是一个有效的 UUID。

示例:

typescript
import { Controller, Get, Param, ParseUUIDPipe } from '@nestjs/common';
import { ProductsService } from './products.service';

@Controller('products')
export class ProductsController {
  constructor(private readonly productsService: ProductsService) {}

  @Get(':uuid')
  async findOne(@Param('uuid', ParseUUIDPipe) uuid: string) {
    // 管道确保了 'uuid' 是一个有效的 UUID 字符串
    return this.productsService.findOne(uuid);
  }
}

和 ParseIntPipe 一样,如果传入的字符串不是有效的 UUID,ParseUUIDPipe 会自动抛出一个异常。

NestJS 还提供了其他几个有用的内置管道,如 ParseBoolPipe、ParseArrayPipe 和 ParseEnumPipe。


3. 使用 class-validator 和 class-transformer 验证 DTOs ✅

对于简单的参数,内置管道非常棒。但对于复杂的请求体(例如,创建一个新用户的 POST 请求),我们需要更强大的功能。

问题: 一个创建用户的请求体可能包含 username, email, password, age 等多个字段,每个字段都有自己的验证规则(例如,email 必须是有效的电子邮件格式,password 必须至少有8个字符)。在控制器中用一堆 if 语句来检查这些,简直是一场噩梦。

解决方案: 我们使用 数据传输对象 (DTOs) 和两个强大的库 class-validator 和 class-transformer。DTO 是一个简单的类,用于定义传入数据的结构或形状。

第1步: 安装依赖

首先,我们需要安装这两个库。

bash
npm install class-validator class-transformer

第2步: 创建一个 DTO

让我们创建一个 CreateUserDto。这是一个定义新用户数据结构的类。我们使用 class-validator 提供的装饰器来声明我们的验证规则。

src/users/dto/create-user.dto.ts

typescript
import { IsString, IsEmail, MinLength, IsInt, Min } from 'class-validator';

export class CreateUserDto {
  @IsString()
  @MinLength(3)
  username: string;

  @IsEmail()
  email: string;

  @IsString()
  @MinLength(8, { message: '密码太短了,至少需要8个字符' })
  password: string;

  @IsInt()
  @Min(18)
  age: number;
}

class-validator 提供了大量的验证装饰器,如 @IsString, @IsInt, @MinLength 等。

第3步: 启用全局 ValidationPipe

为了让我们的 DTO 生效,我们需要使用 NestJS 的 ValidationPipe。最佳实践是在应用程序的入口点(main.ts)将其设置为全局管道。这样,它将保护我们所有的端点。

src/main.ts

typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true, // 自动剥离 DTO 中未定义的属性
      forbidNonWhitelisted: true, // 如果存在未定义的属性,则抛出错误
      transform: true, // 自动将传入的数据转换为 DTO 实例
    }),
  );

  await app.listen(3000);
}
bootstrap();
  • whitelist: true: 这是一个安全功能。它会确保任何未在 DTO 中使用验证装饰器定义的属性都会被自动删除。
  • forbidNonWhitelisted: true: 这会更进一步,如果请求中包含 DTO 未定义的属性,它将直接拒绝请求并抛出错误。
  • transform: true: 这是一个非常强大的选项。它会自动将传入的 JSON 对象转换为我们定义的 DTO 类的实例。这使得类型转换成为可能(例如,将网络请求中的字符串数字转换为 number 类型)。

第4步: 在控制器中使用 DTO

现在,我们可以在控制器中直接使用我们的 DTO。

typescript
import { Controller, Post, Body } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  async create(@Body() createUserDto: CreateUserDto) {
    // 如果请求到达这里,就意味着数据已经通过了
    // CreateUserDto 中定义的所有验证规则。
    // createUserDto 是 CreateUserDto 的一个实例!
    return this.usersService.create(createUserDto);
  }
}

就是这么简单!如果客户端发送的数据不符合 CreateUserDto 的规则,NestJS 会自动返回一个 400 Bad Request 响应,其中包含详细的错误信息,告诉你哪个字段验证失败了。


4. 创建你自己的自定义验证管道 🛠️

虽然 ValidationPipe 非常强大,但有时你可能需要一些内置功能无法满足的、非常具体的验证逻辑。

问题: 假设你想创建一个自定义的验证管道,用于修剪所有传入字符串的空白。或者,你需要一个管道来检查某个值是否在数据库中已存在(这是一种更高级的异步验证)。

解决方案: 我们可以轻松创建自己的管道!一个自定义管道就是一个实现了 PipeTransform 接口的类。

示例: 一个简单的 TrimPipe

让我们创建一个管道,它可以去除请求体中特定字符串字段的前后空格。

src/common/pipes/trim.pipe.ts

typescript
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';

@Injectable()
export class TrimPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    // 我们只对字符串值进行操作
    if (typeof value !== 'string') {
      return value;
    }
    return value.trim();
  }
}

解释:

  • transform(value, metadata) 是 PipeTransform 接口要求我们必须实现的方法。
  • value 是当前正在处理的参数(例如,请求体中的一个字段)。
  • metadata 包含了关于这个参数的元数据(例如,它是 @Body()、@Param() 还是 @Query() 参数)。
  • 在这个方法中,我们检查值是否为字符串,如果是,就调用 .trim() 方法,然后返回处理后的值。如果不是,我们原样返回它。

使用自定义管道:

你可以像使用内置管道一样,在控制器中应用你的自定义管道。

typescript
import { Controller, Post, Body } from '@nestjs/common';
import { TrimPipe } from '../common/pipes/trim.pipe';

@Controller('messages')
export class MessagesController {
  @Post()
  create(@Body('content', TrimPipe) content: string) {
    // 这里的 'content' 字符串已经被 TrimPipe 处理过了
    console.log(`Message content: "${content}"`);
    return { message: 'Message received', content };
  }
}

这是一个简单的例子,但它展示了自定义管道的强大之处。你可以将任何可重用的验证或转换逻辑封装在一个管道中,并在整个应用程序中复用它,保持你的代码整洁、模块化和易于测试。

管道是 NestJS 中一个不可或缺的工具,它能极大地提升你应用程序的健壮性和代码质量。现在,去为你的装配线添加一些质量检查站吧!🎉

额外阅读 📚

Challenge

Challenge Instructions

You are building a product review API for an e-commerce website. To ensure data integrity and consistency, you need to use NestJS Pipes to validate and transform incoming request data. Your task is to implement a DTO for validation, a custom pipe for transformation, and apply them correctly in a controller method.

Task 1: Define the Data Transfer Object (DTO)

Create a class named CreateReviewDto. Using decorators from the class-validator library, add the following validation rules to its properties:

  • rating: Must be an integer with a value between 1 and 5 (inclusive).
  • comment: Must be a string, is optional, and if provided, its maximum length cannot exceed 500 characters.
  • productId: Must be a string that is a valid UUID.

Task 2: Create a Custom Transformation Pipe

Create a custom pipe named ParseCommaSeparatedPipe. This pipe must implement the PipeTransform interface.

  • Its transform method should accept a string input (e.g., "nest, pipe, amazing ") and convert it into an array of strings where each element is trimmed of whitespace and is not an empty string (e.g., ['nest', 'pipe', 'amazing']).
  • If the input value is not a string, the pipe should return the value without any modification.

Task 3: Apply Pipes to the Controller Method

In the ReviewsController, complete the signature of the create method.

  • The method should use the @Body() decorator to receive and validate the CreateReviewDto object (you can assume the ValidationPipe is enabled globally).
  • The method should also accept a query parameter named tags by using the @Query('tags') decorator. Apply your custom ParseCommaSeparatedPipe to this parameter to transform the incoming comma-separated string.

Expected result

Your final code should correctly implement all three tasks within the provided boilerplate. The solution will be a single block of TypeScript code where:

  1. The CreateReviewDto class properties are decorated as follows:
    • rating has @IsInt(), @Min(1), and @Max(5).
    • comment has @IsOptional(), @IsString(), and @MaxLength(500).
    • productId has @IsUUID().
  2. The ParseCommaSeparatedPipe class has a transform method that correctly checks if the input is a string, then splits it by commas, trims whitespace from each part, and filters out any empty strings before returning the resulting array.
  3. The create method signature in ReviewsController is correctly written as:
    typescript
    create(
      @Body() dto: CreateReviewDto,
      @Query('tags', ParseCommaSeparatedPipe) tags: string[]
    )
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.