全书目录

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

第十章:装饰器 —— 给中枢预装固定设施,而不是临时在墙上钉钩子

1 分钟 317 字 第 265 / 962 个阅读单元

Decorator 是 Fastify 另一个非常有辨识度的设计。

你可以把它理解成:
在中枢开业前,先把固定设施装好。

js
fastify.decorate('db', {
  async findShipmentById (id) {
    return { id, status: 'sorted' }
  }
})

fastify.decorateRequest('operator', null)

fastify.addHook('preHandler', async function (request) {
  request.operator = { id: 'OP-01', role: 'dispatcher' }
})

fastify.get('/shipments/:id', async function (request) {
  const shipment = await this.db.findShipmentById(request.params.id)
  return {
    shipment,
    operator: request.operator
  }
})

这里有三种装法:

  • decorate:给 server 装设施
  • decorateRequest:给 request 装字段
  • decorateReply:给 reply 装能力
#为什么不推荐在请求中途随手加字段

坏写法:

js
fastify.addHook('preHandler', async function (request) {
  request.user = { id: 1 }
})

更好的写法:

js
fastify.decorateRequest('user', null)

原因不是“洁癖”,而是运行时优化。
临时改对象形状,会让引擎更难优化;提前声明固定设施,就像在仓库设计图里先画好轨道。

#另一个重要细节

如果你要在 handler 里用 this.db 这类装饰器,请用普通 function,不要用箭头函数。
因为箭头函数不绑定自己的 this