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/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用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 配置语言