I would like to add to the response of @Hailgrim which worked for me but I added types validations or casting for typescript and for saving an array of objects. I hope it will be useful!
- "cache-manager": "^5.2.1"
- "cache-manager-redis-store": "^2.0.0"
- "@nestjs/cache-manager": "^1.0.0",
- "@types/cache-manager-redis-store": "^2.0.1",
redis.module.ts
import { Module } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { CacheModule } from '@nestjs/cache-manager';
import { RedisService } from './redis.service';
const redisModuleFactory = CacheModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
ttl: configService.get('CACHE_TTL'),
store: redisStore,
host: configService.get('CACHE_HOST'),
port: configService.get('CACHE_PORT'),
}),
inject: [ConfigService],
});
@Module({
imports: [redisModuleFactory],
controllers: [],
providers: [RedisService],
exports: [RedisService],
})
export class RedisModule {}
and redis.service.ts
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import {
Inject,
Injectable,
InternalServerErrorException,
Logger,
} from '@nestjs/common';
import { throws } from 'assert';
import { Cache } from 'cache-manager';
@Injectable()
export class RedisService {
private logger = new Logger(RedisService.name);
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
async set(key: string, value: unknown): Promise<void> {
try {
await this.cacheManager.set(`yourglobalkey::${key}`, value);
} catch (error) {
throw new InternalServerErrorException();
}
}
async get<T>(key: string): Promise<T | undefined> {
try {
const jsonData: string | undefined = await this.cacheManager.get<string>(
`yourglobalkey::${key}`,
);
return jsonData ? JSON.parse(jsonData!) : undefined;
} catch (error) {
throw new InternalServerErrorException();
}
}
}
you can call it from outside like... my case an array of objects.
const countries: yourType[] | undefined = await this.redisService.get<
yourType[]
>('yourkey');