react-native-healthkit-bridge
Version:
A comprehensive React Native bridge for Apple HealthKit with TypeScript support, advanced authorization, and flexible data queries
76 lines (75 loc) • 2.49 kB
JavaScript
export class MetricsCollector {
constructor() {
this.metrics = [];
this.maxMetrics = 1000;
}
static getInstance() {
if (!MetricsCollector.instance) {
MetricsCollector.instance = new MetricsCollector();
}
return MetricsCollector.instance;
}
recordOperation(operation, duration, success, error) {
const metric = {
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() {
return [...this.metrics];
}
getOperationMetrics(operation) {
return this.metrics.filter(m => m.operation === operation);
}
getAverageDuration(operation) {
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) {
const operationMetrics = this.getOperationMetrics(operation);
if (operationMetrics.length === 0)
return 0;
const successCount = operationMetrics.filter(m => m.success).length;
return successCount / operationMetrics.length;
}
clearMetrics() {
this.metrics = [];
}
getSummary() {
const operations = [...new Set(this.metrics.map(m => m.operation))];
const summary = {};
operations.forEach(operation => {
summary[operation] = {
avgDuration: this.getAverageDuration(operation),
successRate: this.getSuccessRate(operation),
count: this.getOperationMetrics(operation).length
};
});
return summary;
}
}
export function withMetrics(operation, fn) {
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;
});
}