import { Injectable, OnModuleDestroy, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import Redis from 'ioredis'; @Injectable() export class RedisService implements OnModuleDestroy { private readonly logger = new Logger(RedisService.name); private readonly client: Redis; constructor(private readonly configService: ConfigService) { const password = this.configService.get('REDIS_PASSWORD'); this.client = new Redis({ host: this.configService.get('REDIS_HOST') || 'localhost', port: this.configService.get('REDIS_PORT') || 6379, password: password || undefined, }); this.client.on('connect', () => { this.logger.log('Connected to Redis'); }); this.client.on('error', (err) => { this.logger.error('Redis error:', err); }); } async onModuleDestroy() { await this.client.quit(); } getClient(): Redis { return this.client; } async get(key: string): Promise { return this.client.get(key); } async set(key: string, value: string, ttlSeconds?: number): Promise { if (ttlSeconds) { await this.client.setex(key, ttlSeconds, value); } else { await this.client.set(key, value); } } async del(key: string): Promise { await this.client.del(key); } async exists(key: string): Promise { const result = await this.client.exists(key); return result === 1; } async setJson(key: string, value: any, ttlSeconds?: number): Promise { await this.set(key, JSON.stringify(value), ttlSeconds); } async getJson(key: string): Promise { const value = await this.get(key); return value ? JSON.parse(value) : null; } }