react-native-healthkit-bridge
Version:
A comprehensive React Native bridge for Apple HealthKit with TypeScript support, advanced authorization, and flexible data queries
411 lines (370 loc) • 12.2 kB
text/typescript
import {
CategoryTypeIdentifier,
QuantityTypeIdentifier,
getQuantityUnit
} from '../types/healthkit.types';
import { HealthKitBridge } from '../core/HealthKitBridge';
/**
* Example usage for women's health data
*
* This example shows how to access and manage data related to:
* - Menstrual cycle
* - Pregnancy
* - Lactation
* - Contraception
* - Fertility
*/
export class WomensHealthTracker {
private bridge: HealthKitBridge;
constructor() {
this.bridge = new HealthKitBridge();
}
/**
* Request authorization for women's health data
*/
async requestWomensHealthAuthorization(): Promise<boolean> {
try {
const isAuthorized = await this.bridge.requestReadAuthorization([
// Menstrual cycle data
CategoryTypeIdentifier.MenstrualFlow,
CategoryTypeIdentifier.IntermenstrualBleeding,
CategoryTypeIdentifier.CervicalMucusQuality,
CategoryTypeIdentifier.OvulationTestResult,
// Pregnancy and lactation data
CategoryTypeIdentifier.Pregnancy,
CategoryTypeIdentifier.Lactation,
// Contraception data
CategoryTypeIdentifier.Contraceptive,
// Related data (symptoms, etc.)
CategoryTypeIdentifier.SexualActivity,
CategoryTypeIdentifier.PelvicPain,
CategoryTypeIdentifier.VaginalDryness,
CategoryTypeIdentifier.HotFlashes,
CategoryTypeIdentifier.NightSweats
]);
if (isAuthorized) {
console.log('✅ Authorization for women\'s health data granted');
return true;
} else {
console.log('❌ Authorization for women\'s health data denied');
return false;
}
} catch (error) {
console.error('Error requesting authorization:', error);
return false;
}
}
/**
* Get menstrual cycle data
*/
async getMenstrualCycleData(days: number = 90) {
try {
const [menstrualFlow, intermenstrualBleeding, cervicalMucus] = await Promise.all([
this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.MenstrualFlow,
days
),
this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.IntermenstrualBleeding,
days
),
this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.CervicalMucusQuality,
days
)
]);
return {
menstrualFlow,
intermenstrualBleeding,
cervicalMucus,
cycleLength: this.calculateCycleLength(menstrualFlow),
fertileWindow: this.calculateFertileWindow(menstrualFlow, cervicalMucus)
};
} catch (error) {
console.error('Error getting menstrual cycle data:', error);
return null;
}
}
/**
* Get fertility data
*/
async getFertilityData(days: number = 30) {
try {
const [ovulationTests, cervicalMucus] = await Promise.all([
this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.OvulationTestResult,
days
),
this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.CervicalMucusQuality,
days
)
]);
return {
ovulationTests,
cervicalMucus,
ovulationPrediction: this.predictOvulation(ovulationTests, cervicalMucus)
};
} catch (error) {
console.error('Error getting fertility data:', error);
return null;
}
}
/**
* Get pregnancy data
*/
async getPregnancyData(days: number = 365) {
try {
const pregnancyData = await this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.Pregnancy,
days
);
return {
pregnancyData,
isPregnant: pregnancyData.length > 0 && pregnancyData[pregnancyData.length - 1]?.value === 1,
pregnancyDuration: this.calculatePregnancyDuration(pregnancyData)
};
} catch (error) {
console.error('Error getting pregnancy data:', error);
return null;
}
}
/**
* Get lactation data
*/
async getLactationData(days: number = 365) {
try {
const lactationData = await this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.Lactation,
days
);
return {
lactationData,
isLactating: lactationData.length > 0 && lactationData[lactationData.length - 1]?.value === 1,
lactationDuration: this.calculateLactationDuration(lactationData)
};
} catch (error) {
console.error('Error getting lactation data:', error);
return null;
}
}
/**
* Get contraception data
*/
async getContraceptionData(days: number = 365) {
try {
const contraceptionData = await this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.Contraceptive,
days
);
return {
contraceptionData,
isUsingContraception: contraceptionData.length > 0 && contraceptionData[contraceptionData.length - 1]?.value === 1,
contraceptionMethod: this.getContraceptionMethod(contraceptionData)
};
} catch (error) {
console.error('Error getting contraception data:', error);
return null;
}
}
/**
* Get women's health related symptoms
*/
async getWomensHealthSymptoms(days: number = 30) {
try {
const [pelvicPain, vaginalDryness, hotFlashes, nightSweats] = await Promise.all([
this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.PelvicPain,
days
),
this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.VaginalDryness,
days
),
this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.HotFlashes,
days
),
this.bridge.getCategorySamplesForDays(
CategoryTypeIdentifier.NightSweats,
days
)
]);
return {
pelvicPain,
vaginalDryness,
hotFlashes,
nightSweats,
symptomSummary: this.analyzeSymptoms({
pelvicPain,
vaginalDryness,
hotFlashes,
nightSweats
})
};
} catch (error) {
console.error('Error getting symptoms:', error);
return null;
}
}
/**
* Complete women's health dashboard
*/
async getWomensHealthDashboard() {
try {
const [
cycleData,
fertilityData,
pregnancyData,
lactationData,
contraceptionData,
symptoms
] = await Promise.all([
this.getMenstrualCycleData(90),
this.getFertilityData(30),
this.getPregnancyData(365),
this.getLactationData(365),
this.getContraceptionData(365),
this.getWomensHealthSymptoms(30)
]);
return {
cycle: cycleData,
fertility: fertilityData,
pregnancy: pregnancyData,
lactation: lactationData,
contraception: contraceptionData,
symptoms,
summary: this.generateHealthSummary({
cycleData,
fertilityData,
pregnancyData,
lactationData,
contraceptionData,
symptoms
})
};
} catch (error) {
console.error('Error generating dashboard:', error);
return null;
}
}
// Helper methods for data analysis
private calculateCycleLength(menstrualFlow: any[]): number | null {
if (menstrualFlow.length < 2) return null;
// Logic to calculate cycle length
// Specific implementation depends on returned values
return 28; // Example
}
private calculateFertileWindow(menstrualFlow: any[], cervicalMucus: any[]): any {
// Logic to calculate fertile window
return {
startDate: new Date().toISOString(),
endDate: new Date().toISOString(),
probability: 0.8
};
}
private predictOvulation(ovulationTests: any[], cervicalMucus: any[]): any {
// Logic to predict ovulation
return {
predictedDate: new Date().toISOString(),
confidence: 0.9
};
}
private calculatePregnancyDuration(pregnancyData: any[]): number | null {
if (pregnancyData.length === 0) return null;
// Logic to calculate pregnancy duration
return 280; // Example in days
}
private calculateLactationDuration(lactationData: any[]): number | null {
if (lactationData.length === 0) return null;
// Logic to calculate lactation duration
return 180; // Example in days
}
private getContraceptionMethod(contraceptionData: any[]): string {
if (contraceptionData.length === 0) return 'None';
// Logic to determine contraception method
return 'Pill'; // Example
}
private analyzeSymptoms(symptoms: any): any {
return {
totalSymptoms: Object.values(symptoms).reduce((acc: any[], val: any) => acc.concat(val), []).length,
mostCommon: 'PelvicPain',
severity: 'Moderate'
};
}
private generateHealthSummary(data: any): any {
return {
cycleRegular: data.cycleData?.cycleLength === 28,
fertile: data.fertilityData?.ovulationPrediction?.confidence > 0.7,
pregnant: data.pregnancyData?.isPregnant,
lactating: data.lactationData?.isLactating,
usingContraception: data.contraceptionData?.isUsingContraception,
hasSymptoms: data.symptoms?.symptomSummary?.totalSymptoms > 0
};
}
}
/**
* Practical usage example
*/
export async function womensHealthExample() {
const tracker = new WomensHealthTracker();
// 1. Request authorization
const isAuthorized = await tracker.requestWomensHealthAuthorization();
if (!isAuthorized) {
console.log('❌ Could not obtain authorization');
return;
}
// 2. Get complete dashboard
const dashboard = await tracker.getWomensHealthDashboard();
if (!dashboard) {
console.log('❌ Error getting data');
return;
}
// 3. Show results
console.log('📊 Women\'s Health Dashboard:');
console.log('🩸 Cycle:', dashboard.cycle ? 'Data available' : 'No data');
console.log('🥚 Fertility:', dashboard.fertility ? 'Data available' : 'No data');
console.log('🤱 Pregnancy:', dashboard.pregnancy?.isPregnant ? 'Yes' : 'No');
console.log('🍼 Lactation:', dashboard.lactation?.isLactating ? 'Yes' : 'No');
console.log('💊 Contraception:', dashboard.contraception?.isUsingContraception ? 'Yes' : 'No');
console.log('😷 Symptoms:', dashboard.symptoms?.symptomSummary?.totalSymptoms || 0);
// 4. Health summary
console.log('\n📋 Health Summary:');
console.log('Regular Cycle:', dashboard.summary.cycleRegular ? '✅' : '❌');
console.log('Fertile Period:', dashboard.summary.fertile ? '✅' : '❌');
console.log('Pregnancy:', dashboard.summary.pregnant ? '✅' : '❌');
console.log('Lactation:', dashboard.summary.lactating ? '✅' : '❌');
console.log('Contraception:', dashboard.summary.usingContraception ? '✅' : '❌');
console.log('Symptoms:', dashboard.summary.hasSymptoms ? '⚠️' : '✅');
}
/**
* Available data types for women's health:
*
* 🩸 MENSTRUAL CYCLE:
* - CategoryTypeIdentifier.MenstrualFlow (Menstrual flow)
* - CategoryTypeIdentifier.IntermenstrualBleeding (Intermenstrual bleeding)
* - CategoryTypeIdentifier.CervicalMucusQuality (Cervical mucus quality)
*
* 🥚 FERTILITY:
* - CategoryTypeIdentifier.OvulationTestResult (Ovulation test result)
* - CategoryTypeIdentifier.SexualActivity (Sexual activity)
*
* 🤱 PREGNANCY AND LACTATION:
* - CategoryTypeIdentifier.Pregnancy (Pregnancy)
* - CategoryTypeIdentifier.Lactation (Lactation)
*
* 💊 CONTRACEPTION:
* - CategoryTypeIdentifier.Contraceptive (Contraceptive)
*
* 😷 RELATED SYMPTOMS:
* - CategoryTypeIdentifier.PelvicPain (Pelvic pain)
* - CategoryTypeIdentifier.VaginalDryness (Vaginal dryness)
* - CategoryTypeIdentifier.HotFlashes (Hot flashes)
* - CategoryTypeIdentifier.NightSweats (Night sweats)
*
* 📊 ADDITIONAL DATA:
* - CategoryTypeIdentifier.Headache (Headache)
* - CategoryTypeIdentifier.Fatigue (Fatigue)
* - CategoryTypeIdentifier.MoodChanges (Mood changes)
* - CategoryTypeIdentifier.AppetiteChanges (Appetite changes)
*/