import { Injectable, OnModuleDestroy, OnModuleInit } from "@nestjs/common"; import Redis from "ioredis"; @Injectable() export class RedisService implements OnModuleInit, OnModuleDestroy { private client: Redis; onModuleInit() { this.client = new Redis({ host: process.env.REDIS_HOST || "localhost", port: Number(process.env.REDIS_PORT) || 16379, password: process.env.REDIS_PASSWORD || undefined, }); } onModuleDestroy() { this.client?.disconnect(); } async set(key: string, value: string, ttlSeconds?: number): Promise { if (ttlSeconds) { await this.client.set(key, value, "EX", ttlSeconds); } else { await this.client.set(key, value); } } async get(key: string): Promise { return this.client.get(key); } async del(key: string): Promise { await this.client.del(key); } async incr(key: string, ttlSeconds?: number): Promise { const count = await this.client.incr(key); // Set expiry only on the first increment (count === 1) if (count === 1 && ttlSeconds) { await this.client.expire(key, ttlSeconds); } return count; } async ttl(key: string): Promise { return this.client.ttl(key); } /** * Acquire a distributed lock using Redis SET NX EX * Returns true if lock acquired, false otherwise */ async acquireLock(key: string, ttlSeconds: number = 60): Promise { const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX"); return res === "OK"; } /** * Release a distributed lock */ async releaseLock(key: string): Promise { await this.client.del(`lock:${key}`); } }