使用serverless-auto-swagger时Zod类型推断生成API文档显示空对象问题
解决serverless-auto-swagger与Zod配合时文档显示空对象的问题
问题原因
serverless-auto-swagger生成文档时依赖运行时可访问的schema结构,而z.infer<typeof CheckUrlBodySchema>是TypeScript编译时类型,编译后会被完全移除,插件无法读取到任何字段信息,因此文档中显示为空对象。
解决方案:用Zod直接生成OpenAPI兼容的Schema
通过zod-to-openapi工具将Zod Schema转换为OpenAPI规范的结构,直接提供给serverless-auto-swagger使用,同时保留Zod的验证和类型推断能力。
步骤1:安装依赖
npm install zod-to-openapi
步骤2:扩展Zod并添加OpenAPI元数据
修改你的Schema定义,给字段和对象添加必要的文档描述(可选但推荐):
import { z } from "zod"; import { extendZodWithOpenApi } from "zod-to-openapi"; // 扩展Zod以支持OpenAPI元数据 extendZodWithOpenApi(z); export const CheckUrlBodySchema = z.object({ url: z.string().url().openapi({ description: "需要校验的目标URL", example: "https://example.com" }) }).openapi({ description: "URL校验接口的请求体结构" }); // 保留类型推断,用于代码内的类型提示 export type CheckUrlBody = z.infer<typeof CheckUrlBodySchema>;
步骤3:在Serverless配置中引用转换后的Schema
方式1:Serverless.yml配置
service: your-api-service plugins: - serverless-auto-swagger custom: autoswagger: apiType: httpApi # 根据你的API类型调整,比如restApi functions: checkUrl: handler: src/handlers/checkUrl.handler events: - httpApi: method: POST path: /check-url request: schemas: application/json: ${file(src/schemas/checkUrl.ts):CheckUrlBodySchema.openapi()}
方式2:Serverless.ts配置
import type { AWS } from "@serverless/typescript"; import { CheckUrlBodySchema } from "./src/schemas/checkUrl"; const serverlessConfiguration: AWS = { service: "your-api-service", plugins: ["serverless-auto-swagger"], custom: { autoswagger: { apiType: "httpApi" } }, functions: { checkUrl: { handler: "src/handlers/checkUrl.handler", events: [ { httpApi: { method: "POST", path: "/check-url", request: { schemas: { "application/json": CheckUrlBodySchema.openapi() } } } } ] } } }; module.exports = serverlessConfiguration;
可选:开启插件的Zod自动识别
部分新版本的serverless-auto-swagger支持直接识别Zod Schema,无需手动转换,可以在custom配置中开启:
custom: autoswagger: typefiles: - src/schemas/**/*.ts zodSchemas: true
如果开启后仍有问题,优先使用手动转换的方式,兼容性更稳定。
关键说明
- 不要用
z.infer生成的类型作为文档schema,因为它仅存在于编译阶段,运行时无数据 - 转换后的OpenAPI Schema同时满足文档生成和类型推断需求,无需额外重复定义结构
内容的提问来源于stack exchange,提问作者DeNice
相关产品推荐
相关产品推荐

