stock-bot/libs/data/cache/src/index.ts
2025-06-22 17:55:51 -04:00

53 lines
1.5 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 with trading-optimized defaults
*/
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 types and classes
export type {
CacheConfig,
CacheKey,
CacheOptions,
CacheProvider,
CacheStats,
RedisConfig,
SerializationOptions,
} from './types';
export { RedisConnectionManager } from './connection-manager';
export { CacheKeyGenerator } from './key-generator';
export { RedisCache } from './redis-cache';