node.js - Fastify Swagger,为 Fastify 路由添加标签和描述
我正在使用 fastify 3.28.0(加上 fastify-swagger 插件)和 typescript 4.6.2,我想在每个路由中添加标签、描述和摘要。
来自文档:fastify swagger 可以为每个路由添加描述、标签和摘要。
但我无法做到这一点,因为模式的定义没有提供它们:
export interface FastifySchema {
body?: unknown;
querystring?: unknown;
params?: unknown;
headers?: unknown;
response?: unknown;
}
所以在这种情况下,我不知道如何在 Fastify 路由中定义它们:
const userRoutes: FastifyPluginCallback = (fastify, _opts, done) => {
const findRoute: RouteOptions = {
method: 'GET',
url: '/:username',
schema: {
params: schemaParams,
response: {
200: schema
}
},
handler: (request: FastifyRequest<{
Params: UserRequestFindParams,
}>, reply) => {
const user = find(request.params.username)
reply.send(user)
}
}
fastify.route(findRoute)
done()
}
*** 更新
我刚刚发现 fastify-swagger 的新版本已经发布(fastify-swagger 已被 @fastify/swagger 取代)。在新版本中,上述所有属性都可用。
答案#1
- 使用 Fastify 版本等于 "4.21.x"
- 运行命令
fastify generate project;cd project; npm i - 创建一个文件
plugins/swagger.js
const fp = require('fastify-plugin')
module.exports = fp(async function (fastify, opts) {
await fastify.register(require('@fastify/swagger'), {
swagger: {
info: {
title: 'Admin Api',
description: 'admin api',
version: '0.1.0',
},
basePath: '',
schemes: ['http', 'https'],
consumes: ['application/json'],
produces: ['application/json'],
securityDefinitions: {
Authorization: {
description: 'Authorization header token, sample: "Bearer #TOKEN#"',
type: 'apiKey',
name: 'Authorization',
in: 'header'
}
}
},
})
await fastify.register(require('@fastify/swagger-ui'), {
routePrefix: '/docs',
uiConfig: {
docExpansion: 'none', // expand/not all the documentations none|list|full
deepLinking: true
},
uiHooks: {
onRequest: function (request, reply, next) {
next()
},
preHandler: function (request, reply, next) {
next()
}
},
staticCSP: false,
transformStaticCSP: (header) => header,
exposeRoute: true,
})
fastify.addHook('onRoute', (routeOptions) => {
if (routeOptions.schema && routeOptions.url == '/graphql') {
routeOptions.schema.hide = true
}
});
});
- 创建新文件 routes/test.js
'use strict'
const fastify = require('fastify')();
const schemaPostList = {
description: 'Admin Post List',
tags: ['Admin'],
summary: 'Admin Post List',
security: [{ "Authorization": []}],
querystring: {
page: { type: 'number' },
user: { type: 'string' }
},
};
const schemaPostDetail = {
description: 'Admin Post Detail',
tags: ['Admin'],
summary: 'Admin Post Detail',
security: [{ "Authorization": []}]
};
module.exports = async function (fastify, opts) {
fastify.get('/list', {schema:schemaPostList},async function (request, reply) {
return 'this is an example'
});
}
- 运行命令
npm run dev
它看起来像:
