node.js - 如何将 AsyncLocalStorage 用于 Observable?

标签 node.js rxjs nestjs async-hooks

我想使用 AsyncLocalStorageNestJs Interceptor :

export interface CallHandler<T = any> {
    handle(): Observable<T>;
}
export interface NestInterceptor<T = any, R = any> {
    intercept(context: ExecutionContext, next: CallHandler<T>): Observable<R> | Promise<Observable<R>>;
}
拦截器函数得到一个 next CallHandler返回 Observable .
我无法使用 run在这种情况下(运行回调将在 callHandler.handle() observable 完成之前立即退出):
  intercept(context: ExecutionContext, callHandler: CallHandler): Observable<any> | Promise<Observable<any>> {
    const asyncLocalStorage = new AsyncLocalStorage();
    const myStore = {  some: 'data'};
    return asyncLocalStorage.run(myStore, () => callHandler.handle());
  }
broken replit-example
我想出的解决方案是这样的:
const localStorage = new AsyncLocalStorage();

export class MyInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, callHandler: CallHandler): Observable<any> | Promise<Observable<any>> {
    const resource = new AsyncResource('AsyncLocalStorage', { requireManualDestroy: true });
    const myStore = { some: 'data' };

    localStorage.enterWith(myStore);
    return callHandler.handle().pipe(
      finalize(() => resource.emitDestroy())
    );
  }
}
working replit example
这似乎工作正常,但我不确定这是否真的正确 - 它看起来凌乱且容易出错。所以我想知道:
  • 这是正确的吗?
  • 有没有更好/更清洁的方法来处理这个问题?
  • 最佳答案

    我的使用方式 cls-hooks ,我找到的解决方案是:

    return new Observable(observer => {
      namespace.runAndReturn(async () => {
        namespace.set("some", "data")   
        next.handle()
            .subscribe(
              res => observer.next(res), 
              error => observer.error(error),
              () => observer.complete()
            )
      })
    })
    

    关于node.js - 如何将 AsyncLocalStorage 用于 Observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67136005/

    相关文章:

    node.js - 错误 bcrypt@0.8.3 安装脚本失败 'node-gyp rebuild'

    node.js - 在保存嵌套模式数组之前进行 Mongoose 空值检查

    javascript - 什么是 WebSocket 子协议(protocol)?

    angular - RxJS 在使用 startWith 时跳过去抖动

    node.js - 如何将 HTTP/2 与 Nest.js (Node) 结合使用

    javascript - 翻转操作数时,将空数组与空对象相加会产生不同的结果

    javascript - 为什么数组推送/拼接时可观察结果不会改变

    angular - forkJoin 上的 takeUntil 是否会调用 forkJoined observables 上的函数?

    node.js - Nestjs:导入模块未定义,但可以导入模块中的方法和函数

    passport.js - Nest.js Auth Guard JWT 身份验证不断返回 401 未经授权