You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fastify Swagger枚举生成不符合预期问题咨询

解决Fastify+Typebox生成OpenAPI枚举格式问题

我们在用Fastify结合Typebox定义Schema,通过Fastify Swagger生成OpenAPI文档时,会遇到枚举类型被转成anyOf嵌套单个枚举项的结构(如下),而不是期望的统一string类型+枚举数组格式:

生成的不符合预期的结构:

- schema:
    anyOf:
        - type: string
          enum:
              - sms
        - type: string
          enum:
              - email

期望的结构:

schema:
    type: string
    enum: [sms, email]

两种解决方法:

方法1:使用Typebox的Type.StringEnum定义字符串枚举

Typebox提供了专门的Type.StringEnum方法来定义字符串枚举,能直接生成符合预期的OpenAPI结构:

import { Type } from '@sinclair/typebox';

export const ProviderType = Type.StringEnum({
  SMS: "sms",
  EMAIL: "email"
});

方法2:自定义Fastify Swagger的转换逻辑

如果需要兼容已有的Union定义,可以在注册Fastify Swagger插件时,通过transform选项处理Union类型,将由字符串字面量组成的Union转换成单个string枚举:

fastify.register(require('@fastify/swagger'), {
  openapi: {
    info: {
      title: 'Your API',
      version: '1.0.0'
    }
  },
  transform: ({ schema }) => {
    // 检测是否是由单个字符串枚举项组成的anyOf
    if (schema.anyOf?.every(item => item.type === 'string' && item.enum?.length === 1)) {
      const enumValues = schema.anyOf.map(item => item.enum[0]);
      return {
        ...schema,
        type: 'string',
        enum: enumValues,
        anyOf: undefined // 移除anyOf字段
      };
    }
    return schema;
  }
});

原因说明

之前用Type.Union([Type.Literal(...)])或Type.Enum()生成的结构会被转成anyOf,是因为Typebox的Union类型在OpenAPI规范中默认映射为anyOf,而字符串字面量的Union没有被自动合并为单个枚举数组。使用Type.StringEnum或自定义转换逻辑可以解决这个问题,让文档工具能正确渲染枚举场景。

内容的提问来源于stack exchange,提问作者SamDroid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:45:06