feat: add redis

This commit is contained in:
2026-10-21 11:01:29 +03:00
parent ab2bbeef83
commit 552b74eb95
10 changed files with 240 additions and 9 deletions
+58
View File
@@ -0,0 +1,58 @@
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { readFileSync } from 'fs';
import Redis from 'ioredis';
@Injectable()
export class CacheService implements OnModuleDestroy {
private readonly logger = new Logger('CacheService');
private readonly client: Redis | null;
constructor() {
const url = readCacheUrl();
this.client = url
? new Redis(url, {
enableOfflineQueue: false,
maxRetriesPerRequest: 0,
connectTimeout: 1000,
commandTimeout: 200,
})
: null;
this.client?.on('error', (error) =>
this.logger.warn(`redis unavailable: ${error.message}`),
);
}
async get(key: string): Promise<string | null> {
try {
return (await this.client?.get(key)) ?? null;
} catch {
return null;
}
}
async set(
key: string,
value: string,
ttlMs: number,
onlyIfAbsent = false,
): Promise<void> {
try {
if (onlyIfAbsent) {
await this.client?.set(key, value, 'PX', ttlMs, 'NX');
} else {
await this.client?.set(key, value, 'PX', ttlMs);
}
} catch {
return;
}
}
onModuleDestroy(): void {
this.client?.disconnect();
}
}
function readCacheUrl(): string | undefined {
const file = process.env.CACHE_URL_FILE;
return file ? readFileSync(file, 'utf8').trim() : process.env.CACHE_URL;
}