在 NestJS 中,如何将令牌与使用 registerAsync 注册的模块相关联?
In NestJS how can I associate a token with module registered using registerAsync?
我正在使用 NestJS CacheModule
并使用 registerAsync
注册它以便使用 useFactory
并注入配置模块。
我想提供一个特殊的令牌,因为我打算有多个缓存管理器。 registerAsync
不支持使用 provide
。我怎样才能做到这一点?
代码示例:
import { CacheModule } from '@nestjs/common';
import { ENVALID } from 'nestjs-envalid';
import * as redisStore from 'cache-manager-redis-store';
export const CacheManager1 = CacheModule.registerAsync({
provide: "CACHE_MANAGER_1", //this is not possible
useFactory: async (env: EnvironmentConfig) => {
return {
ttl: env.MANAGER_ONE_TTL_SEC,
store: redisStore,
host: env.MANAGER_ONE_REDIS_HOST,
port: env.MANAGER_ONE_REDIS_PORT,
password: env.MANAGER_ONE_REDIS_PASSWORD,
db: env.MANAGER_ONE_REDIS_DB,
};
},
inject: [ENVALID],
});
与 this question 非常相似,您可以为 this CacheModule 的选项创建一个专用模块,并在新标记下导出 CACHE_MANAGER
。这看起来像
@Module({
imports: [CacheModule.registerAsync(asynCacheManagerOptions)],
providers: [
{
provide: 'CustomCacheToken',
useExisting: CACHE_MANAGER,
}
],
exports: ['CustomCacheToken'],
})
export class CustomCacheModule {}
现在这个缓存管理器可以用@Inject('CustomCacheToken')
注入
我正在使用 NestJS CacheModule
并使用 registerAsync
注册它以便使用 useFactory
并注入配置模块。
我想提供一个特殊的令牌,因为我打算有多个缓存管理器。 registerAsync
不支持使用 provide
。我怎样才能做到这一点?
代码示例:
import { CacheModule } from '@nestjs/common';
import { ENVALID } from 'nestjs-envalid';
import * as redisStore from 'cache-manager-redis-store';
export const CacheManager1 = CacheModule.registerAsync({
provide: "CACHE_MANAGER_1", //this is not possible
useFactory: async (env: EnvironmentConfig) => {
return {
ttl: env.MANAGER_ONE_TTL_SEC,
store: redisStore,
host: env.MANAGER_ONE_REDIS_HOST,
port: env.MANAGER_ONE_REDIS_PORT,
password: env.MANAGER_ONE_REDIS_PASSWORD,
db: env.MANAGER_ONE_REDIS_DB,
};
},
inject: [ENVALID],
});
与 this question 非常相似,您可以为 this CacheModule 的选项创建一个专用模块,并在新标记下导出 CACHE_MANAGER
。这看起来像
@Module({
imports: [CacheModule.registerAsync(asynCacheManagerOptions)],
providers: [
{
provide: 'CustomCacheToken',
useExisting: CACHE_MANAGER,
}
],
exports: ['CustomCacheToken'],
})
export class CustomCacheModule {}
现在这个缓存管理器可以用@Inject('CustomCacheToken')