首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AsyncLocalStorage in Hapi.js

AsyncLocalStorage in Hapi.js
EN

Stack Overflow用户
提问于 2021-10-06 07:43:29
回答 1查看 320关注 0票数 1

我试图在异步存储( onRequest )中添加跟踪id。但是在处理程序中,没有存储的数据。为什么处理程序中的数据是空的?我做错什么了?

异步本地存储:

代码语言:javascript
复制
const {AsyncLocalStorage} = require('async_hooks')
const asyncLocalStorage = new AsyncLocalStorage() 
module.exports = {
  asyncLocalStorage
}

设置:

代码语言:javascript
复制
server.ext({
    type: 'onRequest',
    method(request, h) {
      return new Promise(resolve => {
        getLocalStorage().run({meta: {traceId: 'id'}}, () => {
          return resolve(h.continue)
        })
      })
    },
  })

处理程序:

代码语言:javascript
复制
    {
    path: '/',
    method: 'GET',
    handler: (req) => {
      const data = asyncLocalStorage.getStore()
      //why data is undefined?
      return data;
    },
    options: {
      tags: ['api', 'Test'],
      description: "Test",
      auth: {
        strategy: 'jwt_user',
        scope: ['USER'],
      },
      response: {
        schema: testResponseSchema,
        modify: true,
        options: {
          stripUnknown: true,
          convert: true,
        },
      },
    },
  },
EN

回答 1

Stack Overflow用户

发布于 2022-02-09 09:57:33

我能够让它工作(注意--我仍然在测试这个),它使用了处理程序函数的包装器,如下所示。

步骤1:创建一个文件异步-本地-storage.js

代码语言:javascript
复制
// async-local-storage.js

const { AsyncLocalStorage } = require('async_hooks')

module.exports = {
  asyncLocalStorage: new AsyncLocalStorage(),
}

步骤2:为处理程序函数创建一个包装器

代码语言:javascript
复制
// handle-request.js

const asyncLocalStorage = require('./async-local-storage').asyncLocalStorage

function handleRequest(handler) {
  return (req, h) => {
    const correlationId = req.headers['correlationId']
    return asyncLocalStorage.run({ correlationId : correlationId || 'Not set' }, async () => {
      return handler(req, h)
    })
  }
}

module.exports = {
  handleRequest,
}

步骤3:在每个路由中,使用handleRequest包装器。

代码语言:javascript
复制
// routes.js

const handleRequest = require('./handle-request').handleRequest
const myTestApiHandler = require('./myTestApiHandler').myTestApiHandler

module.exports = [
{
    method: 'GET',
    path: '/api/my-test-api',
    config: {
      handler: handleRequest(myTestApiHandler),
    },
  },
}]

现在,在myTestApiHandler中,我们可以得到如下所示的correlationId。

代码语言:javascript
复制
// myTestApiHandler

const asyncLocalStorage = require('./async-local-storage').asyncLocalStorage

function myTestApiHandler(req, h) {
  const store = asyncLocalStorage.getStore();
  const correlationId = store.correlationId;
  ..
  ..
  
}

module.exports = {
  myTestApiHandler
}

correlationId也应该可以用于从myTestApiHandler函数调用的任何函数,如记录器等。

有关AsyncLocalStorage的更多细节,请参考官方文档

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69461668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档