stock-bot/libs/core/cache/src/index.ts
2025-06-26 16:12:27 -04:00

43 lines
1.4 KiB
TypeScript

import { RedisCache } from './redis-cache';
import type { CacheOptions, CacheProvider } from './types';
// Cache instances registry to prevent multiple instances with same prefix
const cacheInstances = new Map<string, CacheProvider>();
/**
* Create a Redis cache instance
*/
export function createCache(options: CacheOptions): CacheProvider {
const defaultOptions: CacheOptions = {
keyPrefix: 'cache:',
ttl: 3600, // 1 hour default
enableMetrics: true,
shared: true, // Default to shared connections
...options,
};
// For shared connections, reuse cache instances with the same key prefix
if (defaultOptions.shared) {
const cacheKey = `${defaultOptions.keyPrefix}-${defaultOptions.ttl}`;
if (cacheInstances.has(cacheKey)) {
const cachedInstance = cacheInstances.get(cacheKey);
if (!cachedInstance) {
throw new Error(`Expected cache instance ${cacheKey} to exist`);
}
return cachedInstance;
}
const cache = new RedisCache(defaultOptions);
cacheInstances.set(cacheKey, cache);
return cache;
}
// For non-shared connections, always create new instances
return new RedisCache(defaultOptions);
}
// Export only what's actually used
export type { CacheProvider, CacheStats } from './types';
export { NamespacedCache } from './namespaced-cache';
export { createNamespacedCache } from './cache-factory';