added first cache

This commit is contained in:
Bojan Kucera 2025-06-05 07:39:54 -04:00
parent eee6135867
commit 3fc123eca3
9 changed files with 210 additions and 9 deletions

59
libs/cache/src/providers/redis-cache.ts vendored Normal file
View file

@ -0,0 +1,59 @@
import Redis, { RedisOptions } from 'ioredis';
import { CacheProvider, CacheOptions } from '../types';
/**
* Redis-based cache provider implementing CacheProvider interface.
*/
export class RedisCache implements CacheProvider {
private redis: Redis;
private defaultTTL: number;
private keyPrefix: string;
constructor(options: CacheOptions = {}) {
if (options.redisUrl) {
this.redis = new Redis(options.redisUrl);
} else {
this.redis = new Redis(options.redisOptions as RedisOptions);
}
this.defaultTTL = options.ttl ?? 3600; // default 1 hour
this.keyPrefix = options.keyPrefix ?? 'cache:';
}
private getKey(key: string): string {
return `${this.keyPrefix}${key}`;
}
async get<T>(key: string): Promise<T | null> {
const fullKey = this.getKey(key);
const val = await this.redis.get(fullKey);
if (val === null) return null;
try {
return JSON.parse(val) as T;
} catch {
return (val as unknown) as T;
}
}
async set<T>(key: string, value: T, ttl?: number): Promise<void> {
const fullKey = this.getKey(key);
const str = typeof value === 'string' ? (value as unknown as string) : JSON.stringify(value);
const expiry = ttl ?? this.defaultTTL;
await this.redis.set(fullKey, str, 'EX', expiry);
}
async del(key: string): Promise<void> {
await this.redis.del(this.getKey(key));
}
async exists(key: string): Promise<boolean> {
const exists = await this.redis.exists(this.getKey(key));
return exists === 1;
}
async clear(): Promise<void> {
const pattern = `${this.keyPrefix}*`;
const keys = await this.redis.keys(pattern);
if (keys.length) await this.redis.del(...keys);
}
}