全书目录

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

第六章:共享 Schema —— 不同仓区要用同一套箱规

1 分钟 83 字 第 261 / 962 个阅读单元

项目一大,你不可能每条线路都手写一遍同样的包裹规则。
这时就要把规则放进中枢公共标准库。

js
fastify.addSchema({
  $id: 'shipment.base',
  type: 'object',
  required: ['trackingNo', 'weight', 'destination'],
  properties: {
    trackingNo: { type: 'string' },
    weight: { type: 'number' },
    destination: { type: 'string' }
  }
})

fastify.post('/shipments', {
  schema: {
    body: { $ref: 'shipment.base#' }
  }
}, async function (request) {
  return { received: request.body }
})

关系图如下:

text
公共箱规中心
└── shipment.base

各分拣线
├── POST /shipments      -> 引用 shipment.base
├── PUT  /shipments/:id  -> 引用 shipment.base
└── POST /recheck        -> 引用 shipment.base

这一步的价值不只是少写代码,而是让整个物流中枢的规则一致