代码之家  ›  专栏  ›  技术社区  ›  gremo

访问自定义拦截器中的嵌套“injector”

  •  3
  • gremo  · 技术社区  · 7 年前

    我需要访问一个服务(由Nest提供) TypeOrmModule )内部 intercept 功能(重要说明:不作为 constructor 参数!!!)因为 这取决于传递的选项 ( entity 在这种情况下)。

    getRepositoryToken

    export class PaginationInterceptor {
      constructor(private readonly entity: Function) {}
    
      intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
        // Here I want to inject the TypeORM repository.
        // I know how to get the injection token, but not HOW to
        // get the "injector" itself.
        const repository = getRepositoryToken(this.entity);
    
        // stuff...
    
        return call$;
      }
    }
    

    Nest中有“服务容器”的概念吗?这个 github issue 没有帮助我。

    示例用法(控制器操作):

      @Get()
      @UseInterceptors(new PaginationInterceptor(Customer))
      async getAll() {
        // stuff...
      }
    
    2 回复  |  直到 7 年前
        1
  •  6
  •   VinceOPS    7 年前

    关于 (如果你真的想要/需要的话),我想用 mixin 班上的人都能做到。看到了吗 v4 documentation (高级>混合类)。

    import { NestInterceptor, ExecutionContext, mixin, Inject } from '@nestjs/common';
    import { getRepositoryToken } from '@nestjs/typeorm';
    import { Observable } from 'rxjs';
    import { Repository } from 'typeorm';
    
    export function mixinPaginationInterceptor<T extends new (...args: any[]) => any>(entityClass: T) {
      // declare the class here as we can't give it "as-is" to `mixin` because of the decorator in its constructor
      class PaginationInterceptor implements NestInterceptor {
        constructor(@Inject(getRepositoryToken(entityClass)) private readonly repository: Repository<T>) {}
    
        intercept(context: ExecutionContext, $call: Observable<any>) {
          // do your things with `this.repository`
          return $call;
        }
      }
    
      return mixin(PaginationInterceptor);
    }
    

    免责声明

    @UseInterceptors(mixinPaginationInterceptor(YourEntityClass))
    

    如果你对密码有任何疑问,请告诉我。但我认为医生 混合


    或者 getRepository typeorm (传递实体类)。 这不是DI 因此,您必须 spyOn 这个 功能,以便进行正确的测试。


    Execution Context 如金所指。

        2
  •  0
  •   Kim Kern    7 年前

    你可以用 NestFactory 创建 NestApplication 实例注入任何提供程序或控制器。

    例子

    假设您的 AppModule :

    providers: [{provide: 'MyToken', useValue: 'my-value'}]
    

    然后您可以在任何地方使用以下内容注入此提供程序:

    // Creates an instance of the NestApplication
    const application = await NestFactory.create(AppModule);
    
    // Retrieves an instance of either injectable or controller available anywhere, otherwise, throws exception.
    const myValue = application.get('MyToken');
    
    console.log(myValue); // -> my-value
    
    推荐文章