@solutionforest/android-health-connect 0.0.0-stage → 0.3.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AndroidHealthConnect.podspec +20 -0
- package/CHANGELOG.md +202 -0
- package/LICENSE +20 -0
- package/README.md +847 -2
- package/SECURITY.md +99 -0
- package/android/build.gradle +104 -0
- package/android/src/main/AndroidManifest.xml +4 -0
- package/android/src/main/java/com/androidhealthconnect/AggregateMapper.kt +521 -0
- package/android/src/main/java/com/androidhealthconnect/AndroidHealthConnectModule.kt +637 -0
- package/android/src/main/java/com/androidhealthconnect/AndroidHealthConnectPackage.kt +31 -0
- package/android/src/main/java/com/androidhealthconnect/AvailabilitySupport.kt +149 -0
- package/android/src/main/java/com/androidhealthconnect/ChangesMapper.kt +105 -0
- package/android/src/main/java/com/androidhealthconnect/ExtendedRecordMapper.kt +665 -0
- package/android/src/main/java/com/androidhealthconnect/FeatureSupport.kt +88 -0
- package/android/src/main/java/com/androidhealthconnect/PhrMapper.kt +187 -0
- package/android/src/main/java/com/androidhealthconnect/PlannedExerciseMapper.kt +242 -0
- package/android/src/main/java/com/androidhealthconnect/RecordMapper.kt +1222 -0
- package/app.plugin.js +1 -0
- package/docs/assets/logo.jpg +0 -0
- package/ios/AndroidHealthConnect.h +5 -0
- package/ios/AndroidHealthConnect.mm +21 -0
- package/lib/module/NativeAndroidHealthConnect.js +5 -0
- package/lib/module/NativeAndroidHealthConnect.js.map +1 -0
- package/lib/module/foreground.js +117 -0
- package/lib/module/foreground.js.map +1 -0
- package/lib/module/helpers.js +280 -0
- package/lib/module/helpers.js.map +1 -0
- package/lib/module/index.js +354 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/types.js +392 -0
- package/lib/module/types.js.map +1 -0
- package/lib/module/upgrade.js +101 -0
- package/lib/module/upgrade.js.map +1 -0
- package/lib/typescript/package.json +1 -0
- package/lib/typescript/plugin/src/index.d.ts +14 -0
- package/lib/typescript/plugin/src/index.d.ts.map +1 -0
- package/lib/typescript/src/NativeAndroidHealthConnect.d.ts +95 -0
- package/lib/typescript/src/NativeAndroidHealthConnect.d.ts.map +1 -0
- package/lib/typescript/src/foreground.d.ts +43 -0
- package/lib/typescript/src/foreground.d.ts.map +1 -0
- package/lib/typescript/src/helpers.d.ts +108 -0
- package/lib/typescript/src/helpers.d.ts.map +1 -0
- package/lib/typescript/src/index.d.ts +208 -0
- package/lib/typescript/src/index.d.ts.map +1 -0
- package/lib/typescript/src/types.d.ts +1209 -0
- package/lib/typescript/src/types.d.ts.map +1 -0
- package/lib/typescript/src/upgrade.d.ts +26 -0
- package/lib/typescript/src/upgrade.d.ts.map +1 -0
- package/package.json +255 -4
- package/plugin/build/index.d.ts +13 -0
- package/plugin/build/index.js +57 -0
- package/plugin/src/index.ts +105 -0
- package/src/NativeAndroidHealthConnect.ts +133 -0
- package/src/foreground.ts +167 -0
- package/src/helpers.ts +373 -0
- package/src/index.tsx +623 -0
- package/src/types.ts +1525 -0
- package/src/upgrade.ts +155 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
2
|
+
import { AppState } from 'react-native';
|
|
3
|
+
import type { AppStateStatus } from 'react-native';
|
|
4
|
+
import { pollUntil } from './helpers';
|
|
5
|
+
import type { PollUntilOptions, PollUntilResult } from './helpers';
|
|
6
|
+
|
|
7
|
+
export type PollOnForegroundOptions<T> = Omit<
|
|
8
|
+
PollUntilOptions<T>,
|
|
9
|
+
'signal' | 'throwOnTimeout'
|
|
10
|
+
> & {
|
|
11
|
+
/** Called with the final value of each poll (satisfied or soft timeout). */
|
|
12
|
+
onResult: (result: PollUntilResult<T>) => void;
|
|
13
|
+
/** Called when `fetch` rejects. Aborted polls are never reported. */
|
|
14
|
+
onError?: (error: unknown) => void;
|
|
15
|
+
/** Called each time a new poll starts (e.g. to show a spinner). */
|
|
16
|
+
onStart?: () => void;
|
|
17
|
+
/** Poll once right away, not only on the next resume. Default: true. */
|
|
18
|
+
runImmediately?: boolean;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export type ForegroundPoller = {
|
|
22
|
+
/** Abort any in-flight poll and start a new one. */
|
|
23
|
+
refresh: () => void;
|
|
24
|
+
/** Abort any in-flight poll and stop listening to AppState. */
|
|
25
|
+
stop: () => void;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Polls whenever the app becomes `active` (and once immediately), aborting the
|
|
30
|
+
* previous poll on background or re-entry so a stale result never overwrites
|
|
31
|
+
* a newer one. Timeouts are soft: `onResult` gets the last value.
|
|
32
|
+
*/
|
|
33
|
+
export function pollOnForeground<T>(
|
|
34
|
+
fetch: () => Promise<T>,
|
|
35
|
+
options: PollOnForegroundOptions<T>
|
|
36
|
+
): ForegroundPoller {
|
|
37
|
+
const {
|
|
38
|
+
onResult,
|
|
39
|
+
onError,
|
|
40
|
+
onStart,
|
|
41
|
+
runImmediately = true,
|
|
42
|
+
...pollOptions
|
|
43
|
+
} = options;
|
|
44
|
+
let controller: AbortController | undefined;
|
|
45
|
+
let stopped = false;
|
|
46
|
+
|
|
47
|
+
const abort = () => {
|
|
48
|
+
controller?.abort();
|
|
49
|
+
controller = undefined;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const refresh = () => {
|
|
53
|
+
if (stopped) return;
|
|
54
|
+
abort();
|
|
55
|
+
const current = new AbortController();
|
|
56
|
+
controller = current;
|
|
57
|
+
onStart?.();
|
|
58
|
+
pollUntil(fetch, {
|
|
59
|
+
...pollOptions,
|
|
60
|
+
signal: current.signal,
|
|
61
|
+
throwOnTimeout: false,
|
|
62
|
+
}).then(
|
|
63
|
+
(result) => {
|
|
64
|
+
if (!current.signal.aborted) onResult(result);
|
|
65
|
+
},
|
|
66
|
+
(error: unknown) => {
|
|
67
|
+
if (!current.signal.aborted) onError?.(error);
|
|
68
|
+
}
|
|
69
|
+
);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const subscription = AppState.addEventListener(
|
|
73
|
+
'change',
|
|
74
|
+
(state: AppStateStatus) => {
|
|
75
|
+
if (state === 'active') refresh();
|
|
76
|
+
else abort();
|
|
77
|
+
}
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
if (runImmediately) refresh();
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
refresh,
|
|
84
|
+
stop: () => {
|
|
85
|
+
stopped = true;
|
|
86
|
+
abort();
|
|
87
|
+
subscription.remove();
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export type UseForegroundPollOptions<T> = Omit<
|
|
93
|
+
PollOnForegroundOptions<T>,
|
|
94
|
+
'onResult' | 'onError' | 'onStart'
|
|
95
|
+
> & {
|
|
96
|
+
/** Set false to pause (e.g. until permissions are granted). Default: true. */
|
|
97
|
+
enabled?: boolean;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
export type UseForegroundPollState<T> = {
|
|
101
|
+
/** Latest value, kept while a new poll is running. */
|
|
102
|
+
value: T | undefined;
|
|
103
|
+
/** False when the last poll timed out before `ready` — may be a real zero. */
|
|
104
|
+
satisfied: boolean;
|
|
105
|
+
/** True while a poll is in flight. */
|
|
106
|
+
loading: boolean;
|
|
107
|
+
error: unknown;
|
|
108
|
+
refresh: () => void;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* React hook around {@link pollOnForeground}. `fetch` and `ready` may be
|
|
113
|
+
* inline lambdas; only `enabled`, `timeoutMs` and `intervalMs` restart polling.
|
|
114
|
+
*/
|
|
115
|
+
export function useForegroundPoll<T>(
|
|
116
|
+
fetch: () => Promise<T>,
|
|
117
|
+
options: UseForegroundPollOptions<T>
|
|
118
|
+
): UseForegroundPollState<T> {
|
|
119
|
+
const {
|
|
120
|
+
enabled = true,
|
|
121
|
+
ready,
|
|
122
|
+
timeoutMs,
|
|
123
|
+
intervalMs,
|
|
124
|
+
runImmediately = true,
|
|
125
|
+
} = options;
|
|
126
|
+
const fetchRef = useRef(fetch);
|
|
127
|
+
const readyRef = useRef(ready);
|
|
128
|
+
fetchRef.current = fetch;
|
|
129
|
+
readyRef.current = ready;
|
|
130
|
+
|
|
131
|
+
const pollerRef = useRef<ForegroundPoller | undefined>(undefined);
|
|
132
|
+
const [state, setState] = useState<
|
|
133
|
+
Omit<UseForegroundPollState<T>, 'refresh'>
|
|
134
|
+
>({
|
|
135
|
+
value: undefined,
|
|
136
|
+
satisfied: false,
|
|
137
|
+
loading: enabled && runImmediately,
|
|
138
|
+
error: undefined,
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
useEffect(() => {
|
|
142
|
+
if (!enabled) return undefined;
|
|
143
|
+
|
|
144
|
+
const pollOptions: PollOnForegroundOptions<T> = {
|
|
145
|
+
ready: (v) => readyRef.current(v),
|
|
146
|
+
runImmediately,
|
|
147
|
+
onStart: () =>
|
|
148
|
+
setState((s) => ({ ...s, loading: true, error: undefined })),
|
|
149
|
+
onResult: ({ value, satisfied }) =>
|
|
150
|
+
setState({ value, satisfied, loading: false, error: undefined }),
|
|
151
|
+
onError: (error) => setState((s) => ({ ...s, loading: false, error })),
|
|
152
|
+
};
|
|
153
|
+
if (timeoutMs !== undefined) pollOptions.timeoutMs = timeoutMs;
|
|
154
|
+
if (intervalMs !== undefined) pollOptions.intervalMs = intervalMs;
|
|
155
|
+
|
|
156
|
+
const poller = pollOnForeground(() => fetchRef.current(), pollOptions);
|
|
157
|
+
pollerRef.current = poller;
|
|
158
|
+
|
|
159
|
+
return () => {
|
|
160
|
+
poller.stop();
|
|
161
|
+
pollerRef.current = undefined;
|
|
162
|
+
};
|
|
163
|
+
}, [enabled, timeoutMs, intervalMs, runImmediately]);
|
|
164
|
+
|
|
165
|
+
const refresh = useCallback(() => pollerRef.current?.refresh(), []);
|
|
166
|
+
return { ...state, refresh };
|
|
167
|
+
}
|
package/src/helpers.ts
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import {
|
|
2
|
+
checkPermissions,
|
|
3
|
+
getChanges,
|
|
4
|
+
missingPermissions,
|
|
5
|
+
readRecords,
|
|
6
|
+
requestPermissions,
|
|
7
|
+
} from './index';
|
|
8
|
+
import type {
|
|
9
|
+
DeletionChange,
|
|
10
|
+
GetChangesOptions,
|
|
11
|
+
GetChangesResponse,
|
|
12
|
+
HealthPermission,
|
|
13
|
+
HealthRecord,
|
|
14
|
+
ReadRecordsOptions,
|
|
15
|
+
ReadRecordsResponse,
|
|
16
|
+
RecordType,
|
|
17
|
+
TimeRangeFilter,
|
|
18
|
+
UpsertionChange,
|
|
19
|
+
} from './types';
|
|
20
|
+
|
|
21
|
+
// ─── Permissions ──────────────────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
export type EnsurePermissionsResult = {
|
|
24
|
+
granted: HealthPermission[];
|
|
25
|
+
missing: HealthPermission[];
|
|
26
|
+
allGranted: boolean;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Ensures the listed permissions are granted. By default requests any that are
|
|
31
|
+
* missing (shows the HC dialog). Pass `{ requestIfMissing: false }` to only check.
|
|
32
|
+
*/
|
|
33
|
+
export async function ensurePermissions(
|
|
34
|
+
permissions: HealthPermission[],
|
|
35
|
+
options: { requestIfMissing?: boolean } = {}
|
|
36
|
+
): Promise<EnsurePermissionsResult> {
|
|
37
|
+
const { requestIfMissing = true } = options;
|
|
38
|
+
if (permissions.length === 0) {
|
|
39
|
+
return { granted: [], missing: [], allGranted: true };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let missing = await missingPermissions(permissions);
|
|
43
|
+
if (missing.length > 0 && requestIfMissing) {
|
|
44
|
+
await requestPermissions(permissions);
|
|
45
|
+
missing = await missingPermissions(permissions);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const granted = await checkPermissions(permissions);
|
|
49
|
+
return {
|
|
50
|
+
granted,
|
|
51
|
+
missing,
|
|
52
|
+
allGranted: missing.length === 0,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ─── Time ranges ──────────────────────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
/** Inclusive start / exclusive end Instant window ending at `end` (default now). */
|
|
59
|
+
export function timeRangeLastHours(
|
|
60
|
+
hours: number,
|
|
61
|
+
end: Date = new Date()
|
|
62
|
+
): TimeRangeFilter {
|
|
63
|
+
if (!(hours > 0)) {
|
|
64
|
+
throw new Error('timeRangeLastHours: hours must be > 0');
|
|
65
|
+
}
|
|
66
|
+
const start = new Date(end.getTime() - hours * 3600_000);
|
|
67
|
+
return { startTime: start.toISOString(), endTime: end.toISOString() };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Inclusive start / exclusive end Instant window ending at `end` (default now). */
|
|
71
|
+
export function timeRangeLastDays(
|
|
72
|
+
days: number,
|
|
73
|
+
end: Date = new Date()
|
|
74
|
+
): TimeRangeFilter {
|
|
75
|
+
if (!(days > 0)) {
|
|
76
|
+
throw new Error('timeRangeLastDays: days must be > 0');
|
|
77
|
+
}
|
|
78
|
+
const start = new Date(end.getTime() - days * 86400_000);
|
|
79
|
+
return { startTime: start.toISOString(), endTime: end.toISOString() };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Local-calendar "today" from midnight to `now` (device local zone via Date).
|
|
84
|
+
* Useful for steps / calories dashboards.
|
|
85
|
+
*/
|
|
86
|
+
export function timeRangeToday(now: Date = new Date()): TimeRangeFilter {
|
|
87
|
+
const start = new Date(now);
|
|
88
|
+
start.setHours(0, 0, 0, 0);
|
|
89
|
+
return { startTime: start.toISOString(), endTime: now.toISOString() };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// ─── Wait / poll ──────────────────────────────────────────────────────────────
|
|
93
|
+
|
|
94
|
+
export type WaitForRecordsOptions<T extends HealthRecord> = {
|
|
95
|
+
recordType: RecordType;
|
|
96
|
+
timeRangeFilter: TimeRangeFilter;
|
|
97
|
+
dataOriginFilter?: string[];
|
|
98
|
+
/** Stop when at least this many records exist. Default: 1. Ignored if `predicate` is set. */
|
|
99
|
+
minCount?: number;
|
|
100
|
+
/** Custom stop condition (receives the latest page of records). */
|
|
101
|
+
predicate?: (records: T[]) => boolean;
|
|
102
|
+
/** Give up after this many ms. Default: 15000. */
|
|
103
|
+
timeoutMs?: number;
|
|
104
|
+
/** Poll interval. Default: 500. */
|
|
105
|
+
intervalMs?: number;
|
|
106
|
+
signal?: AbortSignal;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
export class WaitTimeoutError extends Error {
|
|
110
|
+
constructor(message: string) {
|
|
111
|
+
super(message);
|
|
112
|
+
this.name = 'WaitTimeoutError';
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** @deprecated Use {@link WaitTimeoutError}. */
|
|
117
|
+
export class WaitForRecordsTimeoutError extends WaitTimeoutError {
|
|
118
|
+
constructor(message: string) {
|
|
119
|
+
super(message);
|
|
120
|
+
this.name = 'WaitForRecordsTimeoutError';
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export type PollUntilOptions<T> = {
|
|
125
|
+
/** Stop when this returns true. */
|
|
126
|
+
ready: (value: T) => boolean;
|
|
127
|
+
/** Give up after this many ms. Default: 15000. */
|
|
128
|
+
timeoutMs?: number;
|
|
129
|
+
/** Poll interval. Default: 500. */
|
|
130
|
+
intervalMs?: number;
|
|
131
|
+
signal?: AbortSignal;
|
|
132
|
+
/**
|
|
133
|
+
* When true (default for {@link waitUntil}), throw {@link WaitTimeoutError}.
|
|
134
|
+
* When false (recommended on AppState resume), return the last value with
|
|
135
|
+
* `satisfied: false` so the UI can keep showing 0 / stale until the next open.
|
|
136
|
+
*/
|
|
137
|
+
throwOnTimeout?: boolean;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
export type PollUntilResult<T> = {
|
|
141
|
+
value: T;
|
|
142
|
+
/** True when `ready(value)` succeeded before timeout. */
|
|
143
|
+
satisfied: boolean;
|
|
144
|
+
attempts: number;
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
function abortError(signal?: AbortSignal): Error {
|
|
148
|
+
const reason =
|
|
149
|
+
signal !== undefined && 'reason' in signal
|
|
150
|
+
? (signal as AbortSignal & { reason?: unknown }).reason
|
|
151
|
+
: undefined;
|
|
152
|
+
return reason instanceof Error ? reason : new Error('Aborted');
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function delay(ms: number, signal?: AbortSignal): Promise<void> {
|
|
156
|
+
return new Promise((resolve, reject) => {
|
|
157
|
+
if (signal?.aborted === true) {
|
|
158
|
+
reject(abortError(signal));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const timer = setTimeout(resolve, ms);
|
|
162
|
+
const onAbort = () => {
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
reject(abortError(signal));
|
|
165
|
+
};
|
|
166
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Generic poller for Health Connect reads/aggregates.
|
|
172
|
+
*
|
|
173
|
+
* HC has **no push**. On real devices, the first read after resume is often
|
|
174
|
+
* empty / `0` until Samsung Health / Fitbit / etc. finish writing into HC —
|
|
175
|
+
* call this (or {@link waitForRecords}) when `AppState` becomes `active`.
|
|
176
|
+
*/
|
|
177
|
+
export async function pollUntil<T>(
|
|
178
|
+
fetch: () => Promise<T>,
|
|
179
|
+
options: PollUntilOptions<T>
|
|
180
|
+
): Promise<PollUntilResult<T>> {
|
|
181
|
+
const {
|
|
182
|
+
ready,
|
|
183
|
+
timeoutMs = 15_000,
|
|
184
|
+
intervalMs = 500,
|
|
185
|
+
signal,
|
|
186
|
+
throwOnTimeout = false,
|
|
187
|
+
} = options;
|
|
188
|
+
|
|
189
|
+
if (timeoutMs <= 0) {
|
|
190
|
+
throw new Error('pollUntil: timeoutMs must be > 0');
|
|
191
|
+
}
|
|
192
|
+
if (intervalMs <= 0) {
|
|
193
|
+
throw new Error('pollUntil: intervalMs must be > 0');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const started = Date.now();
|
|
197
|
+
let attempts = 0;
|
|
198
|
+
let last!: T;
|
|
199
|
+
|
|
200
|
+
for (;;) {
|
|
201
|
+
if (signal?.aborted === true) {
|
|
202
|
+
throw abortError(signal);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
last = await fetch();
|
|
206
|
+
attempts += 1;
|
|
207
|
+
if (ready(last)) {
|
|
208
|
+
return { value: last, satisfied: true, attempts };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const elapsed = Date.now() - started;
|
|
212
|
+
if (elapsed >= timeoutMs) {
|
|
213
|
+
if (throwOnTimeout) {
|
|
214
|
+
throw new WaitTimeoutError(
|
|
215
|
+
`pollUntil timed out after ${timeoutMs}ms (${attempts} attempt(s))`
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
return { value: last, satisfied: false, attempts };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
await delay(Math.min(intervalMs, timeoutMs - elapsed), signal);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Like {@link pollUntil} but throws {@link WaitTimeoutError} on timeout.
|
|
227
|
+
*/
|
|
228
|
+
export async function waitUntil<T>(
|
|
229
|
+
fetch: () => Promise<T>,
|
|
230
|
+
options: Omit<PollUntilOptions<T>, 'throwOnTimeout'>
|
|
231
|
+
): Promise<T> {
|
|
232
|
+
const result = await pollUntil(fetch, { ...options, throwOnTimeout: true });
|
|
233
|
+
return result.value;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Polls {@link readRecords} until records appear (or `predicate` / `minCount`
|
|
238
|
+
* is satisfied), or until timeout. Prefer {@link pollUntil} + `aggregateRecord`
|
|
239
|
+
* when the UI shows a total that starts at `0` after resume.
|
|
240
|
+
*
|
|
241
|
+
* @throws {WaitForRecordsTimeoutError} when `timeoutMs` elapses
|
|
242
|
+
*/
|
|
243
|
+
export async function waitForRecords<T extends HealthRecord>(
|
|
244
|
+
options: WaitForRecordsOptions<T>
|
|
245
|
+
): Promise<ReadRecordsResponse<T>> {
|
|
246
|
+
const {
|
|
247
|
+
recordType,
|
|
248
|
+
timeRangeFilter,
|
|
249
|
+
dataOriginFilter,
|
|
250
|
+
minCount = 1,
|
|
251
|
+
predicate,
|
|
252
|
+
timeoutMs = 15_000,
|
|
253
|
+
intervalMs = 500,
|
|
254
|
+
signal,
|
|
255
|
+
} = options;
|
|
256
|
+
|
|
257
|
+
const readOpts: ReadRecordsOptions = { timeRangeFilter };
|
|
258
|
+
if (dataOriginFilter !== undefined) {
|
|
259
|
+
readOpts.dataOriginFilter = dataOriginFilter;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const waitOpts: Omit<
|
|
263
|
+
PollUntilOptions<ReadRecordsResponse<T>>,
|
|
264
|
+
'throwOnTimeout'
|
|
265
|
+
> = {
|
|
266
|
+
ready: (page) =>
|
|
267
|
+
predicate ? predicate(page.records) : page.records.length >= minCount,
|
|
268
|
+
timeoutMs,
|
|
269
|
+
intervalMs,
|
|
270
|
+
};
|
|
271
|
+
if (signal !== undefined) {
|
|
272
|
+
waitOpts.signal = signal;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
try {
|
|
276
|
+
return await waitUntil(
|
|
277
|
+
() => readRecords<T>(recordType, readOpts),
|
|
278
|
+
waitOpts
|
|
279
|
+
);
|
|
280
|
+
} catch (e) {
|
|
281
|
+
if (e instanceof WaitTimeoutError) {
|
|
282
|
+
throw new WaitForRecordsTimeoutError(
|
|
283
|
+
`waitForRecords timed out after ${timeoutMs}ms waiting for ${recordType}`
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
throw e;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// ─── Pagination / changelog ───────────────────────────────────────────────────
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Follows `pageToken` until exhausted (or `maxPages`). Returns a flat record list.
|
|
294
|
+
*/
|
|
295
|
+
export async function readAllRecords<T extends HealthRecord>(
|
|
296
|
+
recordType: RecordType,
|
|
297
|
+
options: ReadRecordsOptions = {},
|
|
298
|
+
paging: { maxPages?: number } = {}
|
|
299
|
+
): Promise<T[]> {
|
|
300
|
+
const maxPages = paging.maxPages ?? 50;
|
|
301
|
+
const all: T[] = [];
|
|
302
|
+
let pageToken: string | null | undefined = options.pageToken;
|
|
303
|
+
|
|
304
|
+
for (let page = 0; page < maxPages; page++) {
|
|
305
|
+
const res: ReadRecordsResponse<T> = await readRecords<T>(recordType, {
|
|
306
|
+
...options,
|
|
307
|
+
...(typeof pageToken === 'string' && pageToken.length > 0
|
|
308
|
+
? { pageToken }
|
|
309
|
+
: {}),
|
|
310
|
+
});
|
|
311
|
+
all.push(...res.records);
|
|
312
|
+
const next = res.pageToken;
|
|
313
|
+
if (typeof next !== 'string' || next.length === 0) {
|
|
314
|
+
return all;
|
|
315
|
+
}
|
|
316
|
+
pageToken = next;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
return all;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export type PullChangesResult = {
|
|
323
|
+
upsertionChanges: UpsertionChange[];
|
|
324
|
+
deletionChanges: DeletionChange[];
|
|
325
|
+
nextChangesToken: string;
|
|
326
|
+
changesTokenExpired: boolean;
|
|
327
|
+
pagesFetched: number;
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Drains the changelog: loops {@link getChanges} while `hasMore`.
|
|
332
|
+
* Returns merged upserts/deletes and the token to persist.
|
|
333
|
+
*
|
|
334
|
+
* If `changesTokenExpired` is true, stop and backfill with {@link readRecords}
|
|
335
|
+
* before minting a fresh token via {@link getChangesToken}.
|
|
336
|
+
*/
|
|
337
|
+
export async function pullChanges(
|
|
338
|
+
changesToken: string,
|
|
339
|
+
options: GetChangesOptions & { maxPages?: number } = {}
|
|
340
|
+
): Promise<PullChangesResult> {
|
|
341
|
+
const { maxPages = 100, ...changeOpts } = options;
|
|
342
|
+
const upsertionChanges: UpsertionChange[] = [];
|
|
343
|
+
const deletionChanges: DeletionChange[] = [];
|
|
344
|
+
|
|
345
|
+
let token = changesToken;
|
|
346
|
+
let pagesFetched = 0;
|
|
347
|
+
let last: GetChangesResponse | null = null;
|
|
348
|
+
|
|
349
|
+
while (pagesFetched < maxPages) {
|
|
350
|
+
const page = await getChanges(token, changeOpts);
|
|
351
|
+
pagesFetched += 1;
|
|
352
|
+
last = page;
|
|
353
|
+
upsertionChanges.push(...page.upsertionChanges);
|
|
354
|
+
deletionChanges.push(...page.deletionChanges);
|
|
355
|
+
token = page.nextChangesToken;
|
|
356
|
+
|
|
357
|
+
if (page.changesTokenExpired || !page.hasMore) {
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
if (!last) {
|
|
363
|
+
throw new Error('pullChanges: no pages fetched');
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return {
|
|
367
|
+
upsertionChanges,
|
|
368
|
+
deletionChanges,
|
|
369
|
+
nextChangesToken: last.nextChangesToken,
|
|
370
|
+
changesTokenExpired: last.changesTokenExpired,
|
|
371
|
+
pagesFetched,
|
|
372
|
+
};
|
|
373
|
+
}
|