我试图在异步存储( onRequest )中添加跟踪id。但是在处理程序中,没有存储的数据。为什么处理程序中的数据是空的?我做错什么了?
异步本地存储:
const {AsyncLocalStorage} = require('async_hooks')
const asyncLocalStorage = new AsyncLocalStorage()
module.exports = {
asyncLocalStorage
}设置:
server.ext({
type: 'onRequest',
method(request, h) {
return new Promise(resolve => {
getLocalStorage().run({meta: {traceId: 'id'}}, () => {
return resolve(h.continue)
})
})
},
})处理程序:
{
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,
},
},
},
},发布于 2022-02-09 09:57:33
我能够让它工作(注意--我仍然在测试这个),它使用了处理程序函数的包装器,如下所示。
步骤1:创建一个文件异步-本地-storage.js
// async-local-storage.js
const { AsyncLocalStorage } = require('async_hooks')
module.exports = {
asyncLocalStorage: new AsyncLocalStorage(),
}步骤2:为处理程序函数创建一个包装器
// 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包装器。
// 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。
// 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的更多细节,请参考官方文档
https://stackoverflow.com/questions/69461668
复制相似问题