首页 > 其他分享 >fastify-request-context fastify request 级别的存储支持扩展

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

时间:2023-11-14 09:57:40浏览次数:30  
标签:requestContext app request user context fastify

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/

标签:requestContext,app,request,user,context,fastify
From: https://www.cnblogs.com/rongfengliang/p/17830951.html

相关文章

  • pip下载python软件包时报错 Could not find a version that satisfies the requiremen
    pip下载python软件包时报错,使用了国内源等各种方法,后来才知道是电脑中打开了抓包工具;打开抓包工具后一定要关闭抓包工具,这样下载软件包就下载下来了关闭抓包工具后,下载成功了......
  • requests模块实例
    importrequestsimportjsonclassHandleRequest:param_type_dict={'form':'application/x-www-form-urlencoded','data':'application/x-www-form-urlencoded','json':'app......
  • Golang 中的 Context 包
    Golang中的Context包原创 Slagga 技术的游戏 2023-11-1212:28 发表于广东收录于合集#Golang89个简介今天,我们将讨论Go编程中非常重要的一个主题:context 包。如果你现在觉得它很令人困惑,不用担心—在本文结束时,你将像专家一样处理context!想象一下,你在一个......
  • springboot使用requestmapping创建xml响应体接口
    entity下创建类文件,类名分别为:ResponseXml,ResponseItemcontroller下创建xml响应体实现方法getResponseWithXml---------ResponseXmlStart-------importjavax.xml.bind.annotation.*;//根标签@XmlRootElement(name="test1")publicclassResponseXml{privateStringum......
  • Java中的HttpServletRequest
    Request:请求HttpServletRequest请求是获取请求行、请求头和请求体;可以通过这个方法设置防盗链,获取地址。牢记解决乱码的方式。怎么选择是重定向还是转发呢?通常情况下转发更快,而且能保持request内的对象,所以他是第一选择。但是由于在转发之后,浏览器中URL仍然指向开始页面,此......
  • org.springframework.context.ApplicationContextException: Failed to start bean 'd
    这个原因是高版本SpringBoot整合swagger造成的我的项目是2.7.8swagger版本是3.0.0就会出现上面的报错解决方式:1.配置WebMvcConfigurer.javaimportorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.Res......
  • Python 潮流周刊#26:requests3 的现状
    你好,我是猫哥。这里每周分享优质的Python、AI及通用技术内容,大部分为英文。本周刊开源,欢迎投稿。另有电报频道作为副刊,补充发布更加丰富的资讯。......
  • requestAnimationFrame虽然是异步函数,但是由于i是用let定义的,每一次都会生成一个块级
    以下代码执行后,console输出的信息是?for(leti=0;i<5;i++){requestAnimationFrame(()=>console.log(i));}01234requestAnimationFrame虽然是异步函数,但是由于i是用let定义的,每一次都会生成一个块级作用域,来把当前值和requestAnimationFrame放在这个作用域中......
  • A potentially dangerous Request.Form value was detected from the client
    ApotentiallydangerousRequest.Formvaluewasdetectedfromtheclient解决方案一:在.aspx文件头中加入这句:<%@PagevalidateRequest="false" %>解决方案二:修改web.config文件:<configuration> <system.web>   <pagesvalidateRequest="fals......
  • SpringBoot复习:(57)ServletRequestListener
    packagecn.edu.tju.confiig;importorg.springframework.context.annotation.Configuration;importjavax.servlet.ServletRequestEvent;importjavax.servlet.ServletRequestListener;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServlet......