作者:markzzw 时间:2024-2-1
线上代码:CodeSandbox
系列阅读
在 NestJS 开发中,验证和处理传入的请求数据是一项至关重要的任务。为了简化这一过程,NestJS 提供了一个内置的管道叫做 ValidationPipe,它可以帮助我们轻松地进行数据验证和转换。
ValidationPipe 通过定义验证规则和处理逻辑,自动验证传入的请求数据的有效性。这包括验证请求参数、查询参数、请求体和路由参数等。它可以检查数据的类型、长度、格式、范围和自定义规则等,并根据定义的规则进行转换和处理。
使用 ValidationPipe 可以帮助我们减少手动编写验证逻辑的工作量,提高代码的可维护性和可读性。它可以帮助我们有效地防止无效或恶意的输入数据,并提供更好的用户体验。
我们主要讲解三个配置 whitelist
,forbidNonWhitelisted
,transform
。
whitelist
main.ts
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,
}),
);
await app.listen(3000);
}
bootstrap();
这个配置打开时,当我们传入参数不属于我们需要的参数,则会自动过滤,例如:updateCat 的 body 的类型只有 name 和 age 两个,但是如果我们传入不属于 body 类型的参数时,会被过滤掉。
forbidNonWhitelisted
main.ts
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,
forbidNonWhitelisted: true,
}),
);
await app.listen(3000);
}
bootstrap();
whitelist 是负责过滤不需要的参数,那么当我们需要报错当body中有不需要的参数的时候就要用到 forbidNonWhitelisted。
transform
这个配置是帮助转换在路由路径中的参数的属性的,一般在路径中的参数,例如 put 请求的 id 参数的属性在网络传输中会变成 string,如果使用了 transform 然后再将 id 参数改为 number 则nest会把id转变为 number 属性。
在没有打开 transform 配置时,id 会按照 string 进行处理:
在打开 transform 配置时,id 会按照 number 进行处理: