如何在NestJS应用中使用Fastify Validation验证机制?
在NestJS中使用Fastify验证的实现方法
1. 确保项目使用Fastify适配器
NestJS默认使用Express,若要启用Fastify原生验证,需先切换到Fastify适配器:
- 新项目创建时直接指定平台:
nest new your-project --platform fastify - 已有项目先安装依赖:
npm install @nestjs/platform-fastify fastify - 修改
main.ts初始化Fastify应用:
import { NestFactory } from '@nestjs/core'; import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create<NestFastifyApplication>( AppModule, new FastifyAdapter(), ); await app.listen(3000); } bootstrap();
2. 在控制器中配置Fastify验证Schema
NestJS的路由装饰器(如@Post、@Get)支持直接传入Fastify的路由配置选项,包括验证用的schema,完全兼容你提供的原生Fastify写法:
直接在路由装饰器中配置
import { Controller, Post, Body } from '@nestjs/common'; @Controller('user') export class UserController { @Post({ schema: { body: { type: 'object', required: ['name', 'email'], properties: { name: { type: 'string' }, email: { type: 'string', format: 'email' } } } } }) createUser(@Body() body: { name: string; email: string }) { return { hello: body.name }; } }
抽离Schema复用
如果需要在多个地方复用验证规则,可以把Schema抽成单独的常量文件:
// src/user/user.schema.ts export const CreateUserSchema = { body: { type: 'object', required: ['name', 'email'], properties: { name: { type: 'string' }, email: { type: 'string', format: 'email' } } } };
然后在控制器中引入使用:
import { Controller, Post, Body } from '@nestjs/common'; import { CreateUserSchema } from './user.schema'; @Controller('user') export class UserController { @Post({ schema: CreateUserSchema }) createUser(@Body() body: { name: string; email: string }) { return { hello: body.name }; } }
3. 自定义AJV配置(可选)
Fastify默认使用AJV做验证,若需要自定义验证规则、错误信息等,可以在创建FastifyAdapter时传入自定义AJV实例:
import { NestFactory } from '@nestjs/core'; import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'; import { AppModule } from './app.module'; import Ajv from 'ajv'; async function bootstrap() { const ajv = new Ajv({ allErrors: true, // 返回所有验证错误 coerceTypes: true // 自动转换请求数据类型 }); const adapter = new FastifyAdapter({ ajv }); const app = await NestFactory.create<NestFastifyApplication>(AppModule, adapter); await app.listen(3000); } bootstrap();
配置完成后,Fastify会自动按照Schema验证请求数据,不符合规则时会返回400状态码及详细的验证错误信息,和原生Fastify的验证行为完全一致。
内容的提问来源于stack exchange,提问作者alexanne
相关产品推荐
相关产品推荐

