如果你已经写了路由 schema,那就别再手抄另一份接口文档。
Fastify 的自动文档能力,正适合物流中枢这种规则明确的系统。
npm i @fastify/swagger @fastify/swagger-uiawait fastify.register(import('@fastify/swagger'), {
openapi: {
info: {
title: '高速物流中枢 API',
description: '包裹分拣与运单系统',
version: '1.0.0'
}
}
})
await fastify.register(import('@fastify/swagger-ui'), {
routePrefix: '/docs'
})
fastify.get('/shipments/:id', {
schema: {
tags: ['shipments'],
params: {
type: 'object',
properties: {
id: { type: 'string' }
},
required: ['id']
},
response: {
200: {
type: 'object',
properties: {
id: { type: 'string' },
status: { type: 'string' }
}
}
}
}
}, async function (request) {
return { id: request.params.id, status: 'sorted' }
})现在 /docs 就是一份对外操作手册。
关键点是:
Fastify 不是先有文档插件,再硬猜你接口长什么样。
它是你先把线路规则写进 schema,文档自然从规则里长出来。