Sleep API
Access sleep session data, stages, and aggregated statistics.
Methods
HealthX.sleep.getSessions()
Get sleep sessions within a time range.
const sessions = await HealthX.sleep.getSessions({
startDate: '2024-01-01T00:00:00Z',
endDate: '2024-01-31T23:59:59Z',
limit: 30,
ascending: false,
});
Parameters:
interface GetSleepSessionsOptions {
startDate: string; // ISO 8601 format (required)
endDate?: string; // ISO 8601 format (defaults to now)
limit?: number; // Maximum sessions to return
ascending?: boolean; // Sort order (default: false = newest first)
}
Returns: Promise<SleepSession[]>
HealthX.sleep.getLatestSession()
Get the most recent sleep session.
const latest = await HealthX.sleep.getLatestSession();
if (latest) {
console.log('Last sleep:', latest.duration / 3600, 'hours');
}
Returns: Promise<SleepSession | null>
HealthX.sleep.writeSession() (Android only)
Write a new sleep session.
const id = await HealthX.sleep.writeSession({
startTime: '2024-01-15T22:00:00Z',
endTime: '2024-01-16T06:30:00Z',
stages: [
{
type: 'LIGHT',
startTime: '2024-01-15T22:00:00Z',
endTime: '2024-01-15T23:30:00Z',
},
{
type: 'DEEP',
startTime: '2024-01-15T23:30:00Z',
endTime: '2024-01-16T02:00:00Z',
},
{
type: 'REM',
startTime: '2024-01-16T02:00:00Z',
endTime: '2024-01-16T06:30:00Z',
},
],
title: 'Good night',
notes: 'Slept well',
});
Parameters:
interface WriteSleepSessionOptions {
startTime: string; // ISO 8601 format
endTime: string; // ISO 8601 format
stages?: Array<{
type: SleepStageType;
startTime: string;
endTime: string;
}>;
title?: string;
notes?: string;
}
Returns: Promise<string> - The ID of the created session
Throws: Error on iOS (not supported)
HealthX.sleep.deleteSession() (Android only)
Delete a sleep session by ID.
const success = await HealthX.sleep.deleteSession('session-id');
Returns: Promise<boolean>
Throws: Error on iOS (not supported)
HealthX.sleep.aggregate()
Get aggregated sleep statistics.
const stats = await HealthX.sleep.aggregate({
startDate: '2024-01-01T00:00:00Z',
endDate: '2024-01-31T23:59:59Z',
groupBy: 'day',
});
Parameters:
interface AggregateSleepOptions {
startDate: string; // ISO 8601 format
endDate: string; // ISO 8601 format
groupBy?: 'hour' | 'day' | 'week' | 'month';
}
Returns: Promise<SleepAggregateResult>
Types
SleepSession
interface SleepSession {
metadata: {
id: string;
source: {
name: string; // e.g., "Apple Watch" or "Fitbit"
bundleId: string; // e.g., "com.apple.health"
};
createdAt?: string;
modifiedAt?: string;
};
startTime: string; // ISO 8601
endTime: string; // ISO 8601
duration: number; // Total duration in seconds
stages: SleepStage[];
title?: string; // Optional title (Android only)
notes?: string; // Optional notes (Android only)
}
SleepStage
interface SleepStage {
type: SleepStageType;
startTime: string; // ISO 8601
endTime: string; // ISO 8601
duration: number; // Stage duration in seconds
}
type SleepStageType =
| 'UNKNOWN' // Unknown sleep state
| 'AWAKE' // User was awake
| 'IN_BED' // In bed but not sleeping (iOS only)
| 'SLEEPING' // Generic sleeping state
| 'LIGHT' // Light sleep
| 'DEEP' // Deep sleep
| 'REM' // REM sleep
| 'OUT_OF_BED'; // Out of bed (Android only)
SleepAggregateResult
interface SleepAggregateResult {
data: SleepAggregate[];
sources: string[]; // List of data sources
}
interface SleepAggregate {
periodStart: string; // Start of period
periodEnd: string; // End of period
totalDuration: number; // Total sleep in seconds
averageDuration?: number; // Average sleep in seconds
sessionCount: number; // Number of sessions
stageBreakdown?: {
[K in SleepStageType]?: number; // Duration per stage in seconds
};
}
Usage Examples
Get Last Week's Sleep
async function getWeeklySleep() {
const now = new Date();
const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
const sessions = await HealthX.sleep.getSessions({
startDate: weekAgo.toISOString(),
endDate: now.toISOString(),
});
return sessions;
}
Calculate Sleep Quality
function calculateSleepQuality(session: SleepSession) {
const deepTime = session.stages
.filter(s => s.type === 'DEEP')
.reduce((sum, s) => sum + s.duration, 0);
const remTime = session.stages
.filter(s => s.type === 'REM')
.reduce((sum, s) => sum + s.duration, 0);
const awakeTime = session.stages
.filter(s => s.type === 'AWAKE')
.reduce((sum, s) => sum + s.duration, 0);
// Simple quality score based on sleep composition
const qualityScore = (
(deepTime / session.duration) * 40 +
(remTime / session.duration) * 40 +
(1 - awakeTime / session.duration) * 20
) * 100;
return Math.round(qualityScore);
}
Weekly Sleep Report
async function getWeeklySleepReport() {
const now = new Date();
const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
const stats = await HealthX.sleep.aggregate({
startDate: weekAgo.toISOString(),
endDate: now.toISOString(),
groupBy: 'day',
});
const report = stats.data.map(day => ({
date: day.periodStart,
hoursSlept: day.totalDuration / 3600,
deepSleepHours: (day.stageBreakdown?.DEEP || 0) / 3600,
remHours: (day.stageBreakdown?.REM || 0) / 3600,
}));
const avgHours = stats.data.reduce(
(sum, d) => sum + d.totalDuration, 0
) / stats.data.length / 3600;
return {
dailyBreakdown: report,
averageHoursPerNight: avgHours,
sources: stats.sources,
};
}
Platform-Safe Write
async function saveSleepSession(session: WriteSleepSessionOptions) {
if (!HealthX.supportsWrite()) {
console.log('Sleep write not supported on this platform');
return null;
}
return HealthX.sleep.writeSession(session);
}