I am trying to implement a @nestjs/typeorm
like module in nestjs for redis
(for learning and experimenting). I have created a module which connects to a redis
instance.
Using CacheModule.forRoot(options)
I am able to connect successfully but I cannot figure out how to implement forFeature
for this module. I want to import this module in another modules like: CacheModule.forFeature(databaseNumber: number)
. I need the module importing this to use only the database which it is concerned with but the question is How do I get the client instance already initialized by forRoot
and provide the instance returned when I select a database?
import { DynamicModule, Global, Module, Provider } from '@nestjs/common';
import { CacheService } from './cache.service';
import { RedisClientOptions } from 'redis';
@Module({})
export class CacheModule {
static forRoot(options: RedisClientOptions): DynamicModule {
const dataSourceProvider: Provider = {
provide: 'REDIS_CLIENT',
useFactory: async () => {
return await createClient(this.options).connect();
},
};
return {
module: CacheModule,
imports: [],
providers: [dataSourceProvider, CacheService],
exports: [CacheService],
};
}
}