UNPKG

react-native-healthkit-bridge

Version:

A comprehensive React Native bridge for Apple HealthKit with TypeScript support, advanced authorization, and flexible data queries

121 lines (120 loc) 3.6 kB
import { HEALTHKIT_CONFIG } from '../config/healthkit.config'; export class HealthKitCache { constructor() { this.cache = new Map(); this.stats = { hits: 0, misses: 0 }; this.startCleanupInterval(); } static getInstance() { if (!HealthKitCache.instance) { HealthKitCache.instance = new HealthKitCache(); } return HealthKitCache.instance; } set(key, data, ttl = HEALTHKIT_CONFIG.CACHE_TTL) { if (!HEALTHKIT_CONFIG.CACHE_ENABLED) return; // Check cache size limit if (this.cache.size >= HEALTHKIT_CONFIG.CACHE_MAX_SIZE) { this.evictOldest(); } const cachedData = { data, timestamp: Date.now(), ttl, key }; this.cache.set(key, cachedData); } get(key) { if (!HEALTHKIT_CONFIG.CACHE_ENABLED) return null; const cachedData = this.cache.get(key); if (!cachedData) { this.stats.misses++; return null; } // Check if expired if (Date.now() - cachedData.timestamp > cachedData.ttl) { this.cache.delete(key); this.stats.misses++; return null; } this.stats.hits++; return cachedData.data; } has(key) { if (!HEALTHKIT_CONFIG.CACHE_ENABLED) return false; const cachedData = this.cache.get(key); if (!cachedData) return false; // Check if expired if (Date.now() - cachedData.timestamp > cachedData.ttl) { this.cache.delete(key); return false; } return true; } delete(key) { return this.cache.delete(key); } clear() { this.cache.clear(); this.stats = { hits: 0, misses: 0 }; } invalidatePattern(pattern) { const regex = new RegExp(pattern); for (const key of this.cache.keys()) { if (regex.test(key)) { this.cache.delete(key); } } } getStats() { const keys = Array.from(this.cache.keys()); const totalRequests = this.stats.hits + this.stats.misses; const hitRate = totalRequests > 0 ? this.stats.hits / totalRequests : 0; return { hits: this.stats.hits, misses: this.stats.misses, size: this.cache.size, keys, hitRate }; } evictOldest() { let oldestKey = null; let oldestTime = Date.now(); for (const [key, data] of this.cache.entries()) { if (data.timestamp < oldestTime) { oldestTime = data.timestamp; oldestKey = key; } } if (oldestKey) { this.cache.delete(oldestKey); } } startCleanupInterval() { // Clean up expired entries every 5 minutes setInterval(() => { const now = Date.now(); for (const [key, data] of this.cache.entries()) { if (now - data.timestamp > data.ttl) { this.cache.delete(key); } } }, 5 * 60 * 1000); } // Helper methods for common cache keys static createKey(operation, ...params) { return `${operation}:${params.join(':')}`; } static createAuthKey(types) { return `auth:${types.sort().join(',')}`; } static createQueryKey(identifier, unit, days) { return `query:${identifier}:${unit}:${days}`; } }