65 lines
1.7 KiB
TypeScript
65 lines
1.7 KiB
TypeScript
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<void> {
|
|
if (ttlSeconds) {
|
|
await this.client.set(key, value, "EX", ttlSeconds);
|
|
} else {
|
|
await this.client.set(key, value);
|
|
}
|
|
}
|
|
|
|
async get(key: string): Promise<string | null> {
|
|
return this.client.get(key);
|
|
}
|
|
|
|
async del(key: string): Promise<void> {
|
|
await this.client.del(key);
|
|
}
|
|
|
|
async incr(key: string, ttlSeconds?: number): Promise<number> {
|
|
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<number> {
|
|
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<boolean> {
|
|
const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX");
|
|
return res === "OK";
|
|
}
|
|
|
|
/**
|
|
* Release a distributed lock
|
|
*/
|
|
async releaseLock(key: string): Promise<void> {
|
|
await this.client.del(`lock:${key}`);
|
|
}
|
|
}
|