在NestJS结合Fastify使用时如何设置Fastify路由的config配置
NestJS 搭配 Fastify 设置路由 config 的实现方法
你可以通过以下两种常用方式完成 Fastify 路由 config 配置:
方法1:直接在路由装饰器中透传配置
Nest 的 HTTP 方法装饰器(@Get/@Post/@Put等)支持传入第二个参数作为路由配置项,你可以通过 fastify 字段将 Fastify 专属的路由配置透传到底层,其中就包含你需要的 config 属性:
import { Post, Body, Req } from '@nestjs/common'; import type { FastifyRequest } from 'fastify'; @Post('/en', { fastify: { config: { output: 'hello world!' } } }) async createResource( @Body() payload: any, @Req() req: FastifyRequest ): Promise<void> { // 业务逻辑中可以直接从请求对象读取配置 console.log(req.routeOptions.config.output) }
方法2:封装自定义装饰器复用配置
如果有多个路由需要复用相同的config配置,你可以封装自定义装饰器减少重复代码:
import { applyDecorators, SetMetadata } from '@nestjs/common'; import { FASTIFY_ROUTE_CONFIG_METADATA } from '@nestjs/platform-fastify/dist/constants'; // 自定义装饰器 export function FastifyRouteConfig(config: Record<string, any>) { return applyDecorators( SetMetadata(FASTIFY_ROUTE_CONFIG_METADATA, config) ); } // 使用示例 @Post('/en') @FastifyRouteConfig({ output: 'hello world!' }) async createResource( @Body() payload: any, ): Promise<void> {}
内容的提问来源于stack exchange,提问作者mardok
相关产品推荐
相关产品推荐

