我是新来的Fastify,我正试图用它来设置 Swagger 的文档。我使用TypeScript,我发现的所有示例都使用JavaScript和require
语法。
我尝试在可能的情况下遵循示例,现在我的文档没有显示我创建的/
路由的任何内容。
以下是我的当前代码:
import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUi from '@fastify/swagger-ui';
import Fastify from 'fastify';
import { errorBoundary } from './plugins/errorBoundary';
const fastify = Fastify({
logger: true
});
const port = process.env.PORT || 3003;
// Set custom error handler.
fastify.setErrorHandler(errorBoundary);
// Register @fastify/swagger plugin.
fastify.register(fastifySwagger, {
openapi: {
info: {
title: 'Forest Fire API',
description: 'Forest Fire API Documentation',
version: '1.0.0'
},
servers: [
{
url: 'http://localhost'
}
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer'
}
}
},
tags: [
{
name: 'Root',
description: 'Root endpoints'
}
]
}
});
// Register @fastify/swagger-ui plugin.
fastify.register(fastifySwaggerUi, {
routePrefix: '/docs',
uiConfig: {
docExpansion: 'full',
deepLinking: false
},
uiHooks: {
onRequest: function (_request, _reply, next) {
next();
},
preHandler: function (_request, _reply, next) {
next();
}
},
staticCSP: true,
transformStaticCSP: (header) => header,
transformSpecification: (swaggerObject) => {
return swaggerObject;
},
transformSpecificationClone: true
});
// Root route.
fastify.get(
'/',
{
schema: {
description: 'Root endpoint',
tags: ['Root'],
response: {
200: {
description: 'Succesful response',
type: 'object',
properties: {
message: { type: 'string' },
result: { type: 'object', nullable: true }
}
}
}
}
},
async function (request, reply) {
return reply.send({
message: 'Hello World',
result: null
});
}
);
async function start() {
await fastify.listen({
port: port as number
});
fastify.swagger();
}
start().catch((err) => {
fastify.log.error(err);
process.exit(1);
});
当我访问/docs
路由时,显示以下内容:
我希望/
路由会在页面中记录下来。可能的错误有哪些?
1条答案
按热度按时间goucqfw61#
说明
你需要注册route作为插件,以使路由出现在swagger中。
完整代码: