全书目录

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

第七章:序列化 —— 出口打包机决定你最终送出去什么

1 分钟 233 字 第 262 / 962 个阅读单元

很多初学者只盯着“怎么收请求”,却忽略“怎么出响应”。
但真正的物流中枢,出口打包同样关键。

js
fastify.get('/shipments/:id', {
  schema: {
    params: {
      type: 'object',
      required: ['id'],
      properties: {
        id: { type: 'string' }
      }
    },
    response: {
      200: {
        type: 'object',
        properties: {
          id: { type: 'string' },
          status: { type: 'string' },
          etaHours: { type: 'number' }
        }
      }
    }
  }
}, async function (request) {
  return {
    id: request.params.id,
    status: 'in-transit',
    etaHours: 6,
    internalMemo: '不要暴露给客户'
  }
})

虽然 handler 返回了 internalMemo,但最终发出去的只会是响应 schema 里允许的字段。

这就是出口打包机的意义:

text
处理工位产出原始结果
  │
  ▼
响应 schema 过滤
  │
  ▼
只把允许出站的字段打包发走

它带来两层价值:

  • 性能:走高效序列化链路
  • 安全:防止内部字段误出库

再记一个细节:

  • preSerialization 只对要被序列化的对象有效
  • 如果你直接发的是 stringBufferstreamnull,它不会走这道打包工序