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 2023-11-14 09:38  荣锋亮  阅读(27)  评论(0编辑  收藏  举报

导航