nestjs - 如何从 NestJS CacheManager 模块获取 redis io 客户端

标签 nestjs node-redis cachemanager

我目前正在使用 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 然后我想我可以得到客户端。

最佳答案

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

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

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_MANAGER是由createCacheManager创建的,它导入 npm 包 cache-manager,然后使用您提供的存储包调用它的 caching 函数。

我认为您使用的 Cache 类型是从 cache-manager 导入的。类型定义为 here并包含一个包含 hereStore在同一个文件中。 getClient 不是该接口(interface)上的方法方法,因此错误消息是正确的。

但是,由于您正在为商店使用外部包,因此 caching-manager 所知道的还不止这些。查看 cache-manager-redis-store 的类型,您可以看到类型 RedisStore扩展 Store 并包含 getClient

所以 cacheManager 技术上有 getClient 因为你已经用 redis 存储包配置了它,但是你需要在你的 cacheManager 上设置类型> 变量到 RedisCache 以便 TypeScript 允许它。

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

an issue about this same problem在 repo 和there's an issue asking for TypeScript support . TypeScript 目前似乎不正确支持此包。

关于nestjs - 如何从 NestJS CacheManager 模块获取 redis io 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68117902/

相关文章:

angular - CORS 以某种方式阻止了我的 Angular 和 Nestjs 应用程序的通信

javascript - 如何异步查询多条SQL?

node.js - then-redis中如何进行rpush操作?

azure - 如何为 CacheManager 选择 Azure 中的 Redis databaseId?

caching - cachemanager.net - 如何根据传递的键从 Redis 缓存中获取对象列表?

node.js - Nestjs授权时如何提取JWT

nestjs - 有推荐的方法来更新nestjs吗?

sorting - Redis 有序集成员大小和性能

node.js - 交互式地执行操作并且它有效。以编程方式执行相同的操作,但失败了。 Redis、heroku、 Node

azure - 重新启动后连接到 Redis 缓存失败 - Azure