【问题标题】:How to create custom Cache Module in Nest JS如何在 Nest JS 中创建自定义缓存模块
【发布时间】:2023-02-15 21:11:56
【问题描述】:

我想问你如何在 NestJS 中实现自定义 CacheModule。现在该指南包含有关如何将缓存直接连接到 AppModule 应用程序的主模块的信息。但是如果我需要自己定义缓存模块怎么实现呢?

我试图创建类似的东西,但这不是正确的实现,因为例如我想将我的自定义模块作为测试模块的依赖项添加。然后测试不会运行,因为它们根本看不到自定义缓存模块。

自定义缓存模块.ts

@Module({})
export class CustomCacheModule {
  static forRoot(): DynamicModule {
    return {
      imports: [CacheModule.register({ isGlobal: true })],
      module: CustomCacheModule,
      providers: [
        { useClass: CacheService, provide: CACHE_SERVICE },
        { useClass: CalculatorService, provide: CALCULATOR_SERVICE },
        {
          useClass: ExpressionCounterService,
          provide: EXPRESSION_COUNTER_SERVICE,
        },
        {
          useClass: RegExCreatorService,
          provide: REGEXP_CREATOR_SERVICE_INTERFACE,
        },
      ],
      exports: [CustomCacheModule],
    };
  }
}

导入到 AppModule 看起来像这样,我不喜欢我需要调用 forRoot 方法,但这是我在这里找到的唯一实现。

应用程序模块.ts

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    CustomCacheModule.forRoot(),
    DBModule,
    HistoryModule,
    CalculatorModule,
  ],
})
export class AppModule {}

【问题讨论】:

    标签: typescript nestjs


    【解决方案1】:

    可能是您需要将 CustomCacheModule 导入到测试模块中,就像这样

    import { Test, TestingModule } from '@nestjs/testing';
    import { CustomCacheModule } from '../path/to/custom.cache.module';
    
    describe('MyService', () => {
      let service: MyService;
    
      beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          imports: [CustomCacheModule],
          providers: [MyService],
        }).compile();
    
        service = module.get<MyService>(MyService);
      });
    
      it('should be defined', () => {
        expect(service).toBeDefined();
      });
    });
    

    我们正在使用 imports 数组将 CustomCacheModule 导入测试模块,然后添加 MyService 提供程序。这样,测试应该能够看到 CustomCacheModule 并使用它提供的缓存服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 2017-05-19
      • 2015-07-16
      相关资源
      最近更新 更多