我目前正在使用 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并包含一个包含 here 的 Store
在同一个文件中。 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
>redisStoreCacheManagerRedisStore
未导出。
有 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/