Files
canina/backend/src/redis/redis.service.ts
T

44 lines
1.1 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,
});
}
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;
}
}