react-native-healthkit-bridge
Version:
A comprehensive React Native bridge for Apple HealthKit with TypeScript support, advanced authorization, and flexible data queries
155 lines (154 loc) • 6.66 kB
JavaScript
import { QuantityTypeIdentifier, CategoryTypeIdentifier, HealthKitUnit, getQuantityUnit, } from '../types/healthkit.types';
import { HealthKitBridge } from '../core/HealthKitBridge';
/**
* Example usage with full type safety
*
* This example shows the different ways to use the library:
* 1. Full type safety (recommended)
* 2. Using helper function
* 3. Using string (less safe)
*/
export class TypeSafeUsageExample {
constructor() {
this.bridge = new HealthKitBridge();
}
/**
* 1. USO COM TYPE SAFETY COMPLETA (RECOMENDADO)
*
* Para usar type safety completa, você precisa criar uma interface
* que estenda HealthKitBridgeAPI (não HealthKitBridgeAPICompat)
*/
async exampleWithFullTypeSafety() {
// ⚠️ NOTE: This interface needs to be implemented separately
// to have full type safety, because the current HealthKitBridge
// uses HealthKitBridgeAPICompat for compatibility
// Example of how it would be ideal to use:
//
// // ✅ TypeScript ensures the correct unit
// const steps = await this.bridge.getQuantitySamplesForDays(
// QuantityTypeIdentifier.StepCount,
// HealthKitUnit.count, // ✅ Correto
// 7
// );
//
// const heartRate = await this.bridge.getQuantitySamplesForDays(
// QuantityTypeIdentifier.HeartRate,
// HealthKitUnit.beatsPerMinute, // ✅ Correto
// 1
// );
//
// // ❌ TypeScript would complain if using wrong unit
// const wrongSteps = await this.bridge.getQuantitySamplesForDays(
// QuantityTypeIdentifier.StepCount,
// HealthKitUnit.beatsPerMinute, // ❌ Erro de tipo!
// 7
// );
}
/**
* 2. USING HELPER FUNCTION (RECOMMENDED FOR CURRENT USE)
*
* The getQuantityUnit function ensures you use the correct unit
*/
async exampleWithHelperFunction() {
// ✅ Using helper function to get the correct unit
const steps = await this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.StepCount, getQuantityUnit(QuantityTypeIdentifier.StepCount), // ✅ Always correct
7);
const heartRate = await this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.HeartRate, getQuantityUnit(QuantityTypeIdentifier.HeartRate), // ✅ Always correct
1);
const distance = await this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.DistanceWalkingRunning, getQuantityUnit(QuantityTypeIdentifier.DistanceWalkingRunning), // ✅ Always correct
7);
console.log('Steps:', steps);
console.log('Heart rate:', heartRate);
console.log('Distance:', distance);
}
/**
* 3. USING STRING (LESS SAFE, BUT FUNCTIONAL)
*
* You can use strings directly, but lose type safety
*/
async exampleWithStringUnits() {
// ⚠️ Works, but no type checking
const steps = await this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.StepCount, 'count', // ⚠️ String - no verification
7);
const heartRate = await this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.HeartRate, 'bpm', // ⚠️ String - no verification
1);
// ❌ Error at runtime if using wrong unit
const wrongSteps = await this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.StepCount, 'bpm', // ❌ Error - wrong unit for steps
7);
}
/**
* 4. USING CONSTANTS (GOOD COMPROMISE)
*
* Using the exported constants for convenience
*/
async exampleWithConstants() {
// ✅ Using constants for convenience
const steps = await this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.StepCount, HealthKitUnit.count, // ✅ Constant
7);
const heartRate = await this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.HeartRate, HealthKitUnit.beatsPerMinute, // ✅ Constant
1);
const distance = await this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.DistanceWalkingRunning, HealthKitUnit.meters, // ✅ Constant
7);
}
/**
* 5. COMPLETE EXAMPLE OF AUTHORIZATION AND QUERY
*/
async completeExample() {
try {
// Check availability
const isAvailable = await this.bridge.checkAvailability();
if (!isAvailable) {
console.log('HealthKit is not available');
return;
}
// Request authorization
const isAuthorized = await this.bridge.requestReadAuthorization([
QuantityTypeIdentifier.StepCount,
QuantityTypeIdentifier.HeartRate,
CategoryTypeIdentifier.SleepAnalysis
]);
if (!isAuthorized) {
console.log('Authorization denied');
return;
}
// Query data with type safety
const [steps, heartRate, sleep] = await Promise.all([
this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.StepCount, getQuantityUnit(QuantityTypeIdentifier.StepCount), 7),
this.bridge.getQuantitySamplesForDays(QuantityTypeIdentifier.HeartRate, getQuantityUnit(QuantityTypeIdentifier.HeartRate), 1),
this.bridge.getCategorySamplesForDays(CategoryTypeIdentifier.SleepAnalysis, 7)
]);
console.log('Data retrieved successfully:');
console.log('Steps (7 days):', steps.length, 'records');
console.log('Heart rate (1 day):', heartRate.length, 'records');
console.log('Sleep (7 days):', sleep.length, 'records');
}
catch (error) {
console.error('Error:', error);
}
}
}
/**
* SUMMARY OF TYPING OPTIONS:
*
* 1. ✅ Type Safety Completa (Ideal)
* - Interface that forces QuantityTypeToUnit[T]
* - TypeScript detects errors at compile time
* - Requires custom implementation
*
* 2. ✅ Helper Function (Recommended for current use)
* - getQuantityUnit() ensures correct unit
* - Easy to use
* - Type safety at runtime
*
* 3. ✅ Constants (Good compromise)
* - HealthKitUnit.count, HealthKitUnit.beatsPerMinute, etc.
* - Easy to remember
* - Less prone to typing errors
*
* 4. ⚠️ Strings (Functional, but less safe)
* - 'count', 'bpm', 'm', etc.
* - Works, but no type checking
* - Errors only detected at runtime
*
* RECOMMENDATION: Use the helper function getQuantityUnit() for the best balance between ease of use and type safety.
*/