全书目录

第十三篇:Fastify 完全指南 —— 高速物流中枢宇宙

第十三章:自动文档 —— 中枢操作手册应该随线路自动长出来

1 分钟 153 字 第 268 / 962 个阅读单元

如果你已经写了路由 schema,那就别再手抄另一份接口文档。
Fastify 的自动文档能力,正适合物流中枢这种规则明确的系统。

bash
npm i @fastify/swagger @fastify/swagger-ui
js
await 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,文档自然从规则里长出来。