Fastify Swagger 没有在 Swagger UI 中显示我的任何路由,即使直接访问时路由工作正常。我在动态模式下将 Fastify 与
@fastify/swagger
插件一起使用,期望它能够自动拾取路线,但 Swagger JSON 输出显示一个空的 paths
对象。
设置:
描述: 尽管根据 Fastify Swagger 文档设置了所有内容,Swagger UI 仍可访问,但未列出任何路由。路线本身可通过直接 API 调用确认运行(例如,
/ping
返回 pong
)。
简化的代码实现:
// Simplified Fastify setup with Swagger
import fastifySwagger, { type FastifyDynamicSwaggerOptions } from "@fastify/swagger";
import fastifySwaggerUi, { type FastifySwaggerUiOptions } from "@fastify/swagger-ui";
import fastify from "fastify";
// Check if the environment is development or production
const isDevelopment = process.env.NODE_ENV !== "production";
// Create a new instance of fastify
const app = fastify({
logger: isDevelopment
? {
transport: {
target: "pino-pretty",
options: {
translateTime: "HH:MM:ss Z",
ignore: "pid,hostname",
},
},
}
: true,
});
// Define Swagger options
const swaggerOptions: FastifyDynamicSwaggerOptions = {
mode: "dynamic",
openapi: {
openapi: "3.0.0",
info: {
title: "Test API",
description: "API documentation for Test API",
version: "1.0.0",
},
servers: [{ url: "http://localhost:3000", description: "Development server" }],
tags: [{ name: "ping", description: "Ping route to test Swagger integration" }],
},
};
// Define Swagger UI options
const swaggerUiOptions: FastifySwaggerUiOptions = {
routePrefix: "/documentation",
uiConfig: {
docExpansion: "full",
deepLinking: true,
},
};
// ping route
app.get(
"/ping",
{
schema: {
summary: "Ping test",
description: "Ping route to test Swagger integration",
tags: ["ping"],
response: {
200: {
description: "Successful response",
type: "object",
properties: {
pong: {
type: "string",
},
},
},
},
},
},
async (request, reply) => {
return { pong: "pong" };
},
);
// Register Swagger
app.register(fastifySwagger, swaggerOptions);
app.register(fastifySwaggerUi, swaggerUiOptions);
// Start server
app.listen({ port: 3000 }, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server listening at ${address}`);
});
Swagger JSON (
/documentation/json
) 始终显示 "paths": {}
,这表示 Swagger 没有识别任何路由。
{
"openapi":"3.0.0",
"info":{
"title":"Test API",
"description":"API documentation for Test API",
"version":"1.0.0"
},
"components":{
"schemas":{}
},
"paths":{},
"servers":[{
"url":"http://localhost:3000","description":"Development server"
}],
"tags":[{
"name":"ping","description":"Ping route to test Swagger integration"
}]
}
有人遇到过类似的问题,或者可以发现我的设置中可能缺少或配置错误的内容吗?
尝试解决:
这些步骤都没有解决问题。
您应该将路由注册为插件。
试试这个
app.register((app, options, done) => {
// ping route
app.get(
'/ping',
{
schema: {
summary: 'Ping test',
description: 'Ping route to test Swagger integration',
tags: ['ping'],
response: {
200: {
description: 'Successful response',
type: 'object',
properties: {
pong: {
type: 'string'
}
}
}
}
}
},
async (request, reply) => {
return { pong: 'pong' };
}
);
done();
});