59 lines
1.3 KiB
TypeScript
59 lines
1.3 KiB
TypeScript
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;
|
|
}
|