很多初学者只盯着“怎么收请求”,却忽略“怎么出响应”。
但真正的物流中枢,出口打包同样关键。
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 里允许的字段。
这就是出口打包机的意义:
处理工位产出原始结果
│
▼
响应 schema 过滤
│
▼
只把允许出站的字段打包发走它带来两层价值:
- 性能:走高效序列化链路
- 安全:防止内部字段误出库
再记一个细节:
preSerialization只对要被序列化的对象有效- 如果你直接发的是
string、Buffer、stream、null,它不会走这道打包工序