【发布时间】:2019-03-07 21:38:48
【问题描述】:
我想在我的 TypeScript 应用程序中利用 CLS(连续本地存储),这样我就可以在某个地方放置元数据(例如用户 ID、请求 ID)以用于各种用途(例如日志记录),而无需将数据传入每个方法调用。
我尝试同时使用cls-hooked 和async-local-storage。但是,我无法从我的 Jest 单元测试中得到任何工作。
const als = require('async-local-storage');
als.enable();
// ... some code
describe('Authorization tests', () => {
test('Cannot call without correct scope', () => {
als.set('id', "123123123123");
expect(() => service.registerApp(ctxt, app)).toThrowError(AuthorizationError.NOT_AUTHORIZED);
});
});
以上设置基准id没有失败。
export function authorize(requiredPermissions: string[]) {
return (target: any, name: any, descriptor: any) => {
const protectedFunction = descriptor.value;
const als = require('async-local-storage');
console.log(`>>>>>>>>>My ID ${als.get('id')}`);
// ... some code
}
}
但是上面的代码只是简单的输出:
>>>>>>>>>My ID null
我正在尝试的可能吗?提前致谢。
【问题讨论】:
标签: javascript node.js typescript jestjs