fastify-request-context fastify request 级别的存储支持扩展

fastify-request-context 是一个fastify插件基于nodejs 的async hooks 的处理,比较方便,尤其我们是需要进行基于request 进行一些扩展的时候
实际上不少框架都类似类似的能力(比如java web 框架的httpServletSession, sparkjava 的request attribute)

参考使用

  • 注册以及使用
 
const { fastifyRequestContextPlugin, requestContext } = require('@fastify/request-context')
const fastify = require('fastify');
 
const app = fastify({ logger: true })
// 注册插件
app.register(fastifyRequestContextPlugin, { 
  defaultStoreValues: {
    user: { id: 'system' } 
  }
});
// 进行request 数据设置
app.addHook('onRequest', (req, reply, done) => {
  // Overwrite the defaults.
  // This is completely equivalent to using app.requestContext or just requestContext 
  req.requestContext.set('user', { id: 'helloUser' });
  done();
});
 
// this should now get `helloUser` instead of the default `system`
app.get('/', (req, reply) => {
// 获取request context 数据
  // requestContext singleton exposed by the library retains same request-scoped values that were set using `req.requestContext`
  const user = requestContext.get('user');
  reply.code(200).send( { user });
});
 
app.get('/decorator', function (req, reply) {
// 获取request context 数据
  // requestContext singleton exposed as decorator in the fastify instance and can be retrieved:
  const user = this.requestContext.get('user'); // using `this` thanks to the handler function binding
  const theSameUser = app.requestContext.get('user'); // directly using the `app` instance
  reply.code(200).send( { user });
});
 
app.listen({ port: 3000 }, (err, address) => {
  if (err) throw err
  app.log.info(`server listening on ${address}`)
});
 
return app.ready()

参考资料

https://github.com/fastify/fastify-request-context
https://nodejs.org/api/async_hooks.html
https://sparkjava.com/

posted on   荣锋亮  阅读(29)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-11-14 Delta Sharing 最近新特性
2021-11-14 haproxy dataplaneapi
2021-11-14 apache kyuubi + dremio 集成试用
2021-11-14 apache kyuubi 参考架构集成
2020-11-14 tanka 基本试用
2020-11-14 godoc的写法
2020-11-14 tanka灵活可重用的k8s 配置语言

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示