UNPKG

react-native-healthkit-bridge

Version:

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

101 lines (83 loc) 2.81 kB
export interface HealthKitMetrics { operation: string; duration: number; success: boolean; error?: string; timestamp: number; } export class MetricsCollector { private static instance: MetricsCollector; private metrics: HealthKitMetrics[] = []; private maxMetrics = 1000; private constructor() {} static getInstance(): MetricsCollector { if (!MetricsCollector.instance) { MetricsCollector.instance = new MetricsCollector(); } return MetricsCollector.instance; } recordOperation(operation: string, duration: number, success: boolean, error?: string): void { const metric: HealthKitMetrics = { operation, duration, success, error, timestamp: Date.now() }; this.metrics.push(metric); if (this.metrics.length > this.maxMetrics) { this.metrics = this.metrics.slice(-this.maxMetrics); } } getMetrics(): HealthKitMetrics[] { return [...this.metrics]; } getOperationMetrics(operation: string): HealthKitMetrics[] { return this.metrics.filter(m => m.operation === operation); } getAverageDuration(operation: string): number { const operationMetrics = this.getOperationMetrics(operation); if (operationMetrics.length === 0) return 0; const totalDuration = operationMetrics.reduce((sum, m) => sum + m.duration, 0); return totalDuration / operationMetrics.length; } getSuccessRate(operation: string): number { const operationMetrics = this.getOperationMetrics(operation); if (operationMetrics.length === 0) return 0; const successCount = operationMetrics.filter(m => m.success).length; return successCount / operationMetrics.length; } clearMetrics(): void { this.metrics = []; } getSummary(): Record<string, { avgDuration: number; successRate: number; count: number }> { const operations = [...new Set(this.metrics.map(m => m.operation))]; const summary: Record<string, { avgDuration: number; successRate: number; count: number }> = {}; operations.forEach(operation => { summary[operation] = { avgDuration: this.getAverageDuration(operation), successRate: this.getSuccessRate(operation), count: this.getOperationMetrics(operation).length }; }); return summary; } } export function withMetrics<T>( operation: string, fn: () => Promise<T> ): Promise<T> { const startTime = Date.now(); const metrics = MetricsCollector.getInstance(); return fn() .then(result => { const duration = Date.now() - startTime; metrics.recordOperation(operation, duration, true); return result; }) .catch(error => { const duration = Date.now() - startTime; metrics.recordOperation(operation, duration, false, error.message); throw error; }); }