【问题标题】:How can I get redis io client from NestJS CacheManager module如何从 NestJS CacheManager 模块获取 redis io 客户端
【发布时间】:2021-06-24 14:41:27
【问题描述】:

我目前正在使用 NestJS 的缓存管理器模块,我想知道为什么我不能像这样获得 NodeRedis 客户端:

 constructor(
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
  ) {
    cacheManager.store.getClient();
  }

我收到此错误:

ERROR in [...].controller.ts:24:24
TS2339: Property 'getClient' does not exist on type 'Store'.
    22 |     @Inject(CACHE_MANAGER) private cacheManager: Cache,
    23 |   ) {
  > 24 |     cacheManager.store.getClient();
       |                        ^^^^^^^^^
    25 |   }

我在注册 CacheModule 时确实配置了 cache-manager-redis-store,然后我想我可以获取客户端。

【问题讨论】:

    标签: nestjs node-redis cachemanager


    【解决方案1】:

    tl;dr 似乎 cache-manager-redis-store 不被 TypeScript 正确支持,因为 RedisCache 类型是私有的,无法导入。

    作为一种解决方法,您可以将私有类型复制到您自己的文件中:

    import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
    import { Store } from 'cache-manager';
    import Redis from 'redis';
    
    interface RedisCache extends Cache {
      store: RedisStore;
    }
    
    interface RedisStore extends Store {
      name: 'redis';
      getClient: () => Redis.RedisClient;
      isCacheableValue: (value: any) => boolean;
    }
    
    @Injectable()
    export class CacheService {
      constructor(
        @Inject(CACHE_MANAGER)
        private cacheManager: RedisCache,
      ) {
        cacheManager.store.getClient();
      }
    }

    深入了解

    看起来NestJS提供的CACHE_MANAGERcreateCacheManager创建的,它导入npm包cache-manager,然后用你给的store包调用它的caching函数。

    我认为您使用的 Cache 类型是从 cache-manager 导入的。该类型定义为here,并在同一文件中包含Store 包含heregetClient不是那个接口上的method方法,所以报错信息是正确的。

    但是,由于您使用的是商店的外部包,所以它比caching-manager 知道的要多。查看cache-manager-redis-store 的类型,您可以看到RedisStore 扩展了Store 并包含getClient

    所以cacheManager 在技术上具有getClient,因为您已经使用 redis 存储包对其进行了配置,但是您需要将 cacheManager 变量上的类型设置为 RedisCache 以便 TypeScript 允许它。

    基于cache-manager-redis-store 的DefinitelyTyped 类型,如果您将包导入为redisStore,您的类型似乎应该是redisStore.CacheManagerRedisStore.RedisCache,但似乎存在问题,因为该命名空间CacheManagerRedisStore 未导出。

    回购中有an issue about this same problemthere's an issue asking for TypeScript support。目前 TypeScript 似乎没有正确支持这个包。

    【讨论】:

    • 我得到错误 cacheManager.store.getClient is not a function
    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 2015-07-04
    • 2018-05-31
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    相关资源
    最近更新 更多