import { CACHE_MANAGER, Cache } from '@nestjs/cache-manager'; import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common'; @Injectable() export class CacheService implements OnModuleInit { private readonly logger = new Logger(CacheService.name); constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {} async onModuleInit() { ; this.logger.log(`Active Cache Store: ${JSON.stringify(this.cacheManager as any)}`); // Should log 'Keyv' or 'KeyvRedis'. If it says 'Memory', the config is still wrong. this.logger.log('Pinging Redis to check connection...'); try { await this.set('ping', 'pong', 10); // TTL in seconds const result = await this.get('ping'); if (result === 'pong') { this.logger.log('✅ Redis connection successful (set/get test passed).'); } else { this.logger.error(`❌ Redis connection test failed. Expected 'pong', got '${result}'.`); } await this.del('ping'); } catch (error: any) { this.logger.error('❌ Failed to connect to Redis during ping test:', error.message); } } /** Get value from cache */ async get(key: string): Promise { return await this.cacheManager.get(key); } /** Set value in cache with TTL in seconds */ async set(key: string, value: any, ttlSeconds: number) { // cache-manager expects TTL in seconds await this.cacheManager.set(key, value, ttlSeconds * 1000); } /** Delete a key from cache */ async del(key: string) { await this.cacheManager.del(key); } /** Get remaining TTL in seconds */ async getTtl(key: string): Promise { return await this.cacheManager.ttl(key); } }