【Nestjs学习日记】ValidationPipe

作者:markzzw 时间:2024-2-1

线上代码:CodeSandbox

Github:zhangzewei/nest-learning-tutorial
系列阅读

  1. 【Nestjs学习日记】初识nestjs
  2. 【Nestjs学习日记】Nest Controller
  3. 【Nestjs学习日记】抛出异常
  4. 【Nestjs学习日记】Module

在 NestJS 开发中,验证和处理传入的请求数据是一项至关重要的任务。为了简化这一过程,NestJS 提供了一个内置的管道叫做 ValidationPipe,它可以帮助我们轻松地进行数据验证和转换。

ValidationPipe 通过定义验证规则和处理逻辑,自动验证传入的请求数据的有效性。这包括验证请求参数、查询参数、请求体和路由参数等。它可以检查数据的类型、长度、格式、范围和自定义规则等,并根据定义的规则进行转换和处理。

使用 ValidationPipe 可以帮助我们减少手动编写验证逻辑的工作量,提高代码的可维护性和可读性。它可以帮助我们有效地防止无效或恶意的输入数据,并提供更好的用户体验。

我们主要讲解三个配置 whitelist,forbidNonWhitelisted,transform。

whitelist

main.ts

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

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 进行处理:

相关推荐
溪语流沙2 分钟前
【每天一个CSS | Day19】流光文字与一笔写成的手写签名
前端·javascript·css
逐光者9339 分钟前
STM32——SPI 屏 · Flash · 高速
java·前端·stm32
To_OC17 分钟前
同样是让 AI 写全栈,为什么别人一句话就够了
前端·前端框架·next.js
CDwenhuohuo30 分钟前
electron pc项目打包成桌面端
前端·javascript·electron
前端大斗师32 分钟前
「大于 1000」把 1000 元那单也算进去了:我在 Vue3 订单页对了 10 句话
前端·人工智能·typescript·大模型·原力计划
Jmyd01231 小时前
用 Web VR 引擎搭建 3D 虚拟展厅:从素材上云到多端实时渲染的完整数据链路
前端·3d·vr·三维数字化
刘天远2 小时前
Agent成本核算实现:事件表、状态分布与Python归集
前端·数据库·人工智能·python
欣欣之王来了2 小时前
开发环境准备:Node.js、npm、VS Code安装配置
前端·学习·架构·项目·vue3教程
xiaolinudao1232 小时前
将多个 Excel 表格中的数据合并到单个表中|6 种实现方案全解析
java·前端·excel
LRL_3 小时前
跨平台 Node 模块安装指南:如何利用 pnpm/npm 配置`supportedArchitectures` 锁定平台依赖
前端·npm·node.js