推荐答案
// www.javascriptcn.com code example
const fastify = require('fastify')({ logger: true });
const fastifySwagger = require('fastify-swagger');
// 注册 fastify-swagger 插件
fastify.register(fastifySwagger, {
routePrefix: '/documentation',
swagger: {
info: {
title: 'My API',
description: 'API documentation',
version: '1.0.0'
},
externalDocs: {
url: 'https://swagger.io',
description: 'Find more info here'
},
host: 'localhost:3000',
schemes: ['http'],
consumes: ['application/json'],
produces: ['application/json'],
tags: [
{ name: 'user', description: 'User related end-points' },
{ name: 'code', description: 'Code related end-points' }
],
definitions: {
User: {
type: 'object',
required: ['id', 'name'],
properties: {
id: { type: 'string', format: 'uuid' },
name: { type: 'string' },
age: { type: 'integer' }
}
}
},
securityDefinitions: {
apiKey: {
type: 'apiKey',
name: 'apiKey',
in: 'header'
}
}
},
exposeRoute: true
});
// 定义一个路由
fastify.get('/user/:id', {
schema: {
description: 'Get a user by id',
tags: ['user'],
params: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'user id'
}
}
},
response: {
200: {
description: 'Successful response',
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' }
}
}
}
}
}, (request, reply) => {
reply.send({ id: request.params.id, name: 'John Doe' });
});
// 启动服务器
fastify.listen(3000, (err, address) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info(`Server listening on ${address}`);
});本题详细解读
1. 安装 fastify-swagger 插件
首先,你需要安装 fastify-swagger 插件。可以通过以下命令安装:
npm install fastify-swagger
2. 注册 fastify-swagger 插件
在 Fastify 应用中注册 fastify-swagger 插件时,你需要传递一个配置对象。这个配置对象包含了 Swagger 文档的基本信息,如 API 的标题、描述、版本号等。
// www.javascriptcn.com code example
fastify.register(fastifySwagger, {
routePrefix: '/documentation',
swagger: {
info: {
title: 'My API',
description: 'API documentation',
version: '1.0.0'
},
// 其他配置项...
},
exposeRoute: true
});3. 定义路由和 Schema
在 Fastify 中,你可以通过定义路由和 Schema 来生成 Swagger 文档。每个路由都可以有一个 schema 对象,用于描述该路由的输入和输出。
// www.javascriptcn.com code example
fastify.get('/user/:id', {
schema: {
description: 'Get a user by id',
tags: ['user'],
params: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'user id'
}
}
},
response: {
200: {
description: 'Successful response',
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' }
}
}
}
}
}, (request, reply) => {
reply.send({ id: request.params.id, name: 'John Doe' });
});4. 启动服务器并访问 Swagger 文档
启动 Fastify 服务器后,你可以通过访问 /documentation 路径来查看生成的 Swagger 文档。
fastify.listen(3000, (err, address) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info(`Server listening on ${address}`);
});5. 访问 Swagger UI
启动服务器后,打开浏览器并访问 http://localhost:3000/documentation,你将看到生成的 Swagger UI 界面,其中包含了所有定义的路由和 Schema 信息。