Files
HealthLog/src/lib/whoop/sync-cycle.ts
T
Marc-André Bombeck 7e54b6be81 refactor(integrations): split the provider clients into wire types, endpoints and mappers
Oura, Polar, WHOOP and Strava each keep the transport and endpoints in
`client.ts` and gain `wire-types.ts` (the record shapes) and `map.ts` (the
pure record-to-row mappers, no I/O). Google Health's 1,600-line client
becomes `budget.ts` (slice budget and outcome tally), `request.ts` (error
detail, retry, rate limits), `data-points.ts` (the paginated walker) and a
small `client.ts` for the profile and roll-up reads; its `export * from
"./mappers"` facade is gone and its importers name the module that defines
what they use.

The code moved verbatim; the mapper goldens written before the move and
the provider integration tests pass unchanged.
2026-10-23 13:30:10 +02:00

71 lines
2.3 KiB
TypeScript

/**
* WHOOP cycle (day) sync. There is NO webhook for cycles — this is poll-only,
* driven by the hourly fallback cron. Maps each scored cycle via `mapCycle`
* (DAY_STRAIN + ENERGY_EXPENDITURE_KJ) and upserts as `source = WHOOP`.
*
* Cycle id is an int64 (not a UUID); externalId = `cycle:<id>:<fieldTag>`.
*/
import { fetchCycles } from "./client";
import { mapCycle } from "./map";
import {
getValidToken,
incrementalStart,
handleCollectionFetchError,
markResourceSynced,
resolveResourceCursor,
upsertWhoopMeasurements,
WHOOP_RECOVERY_SLEEP_OVERLAP_MS,
type WhoopMeasurementUpsert,
} from "./sync-core";
import { prisma } from "@/lib/db";
export async function syncUserCycle(
userId: string,
opts: { fullSync?: boolean } = {},
): Promise<number> {
const tokenInfo = await getValidToken(userId);
if (!tokenInfo) return 0;
const connection = await prisma.whoopConnection.findUnique({
where: { userId },
select: { lastSyncedAt: true, resourceCursors: true },
});
if (!connection) return 0;
// WHOOP re-scores a cycle THROUGH the day (day strain + energy accrue and
// settle after the fact) and the collection filters on the cycle's own time
// range, not on when it updated — so a narrow 1 h overlap could step the
// cursor past a cycle still being revised and miss the final value. Ride the
// same 7-day re-score overlap workout/recovery/sleep already use; one cycle
// per day means ~7 records re-fetched per tick (one page), and the
// `cycle:<id>:<fieldTag>` upsert keeps the overwrite idempotent.
const start = incrementalStart(resolveResourceCursor(connection, "cycle"), {
fullSync: opts.fullSync,
overlapMs: WHOOP_RECOVERY_SLEEP_OVERLAP_MS,
});
let records: Awaited<ReturnType<typeof fetchCycles>>;
try {
records = await fetchCycles(tokenInfo.accessToken, { start });
} catch (err) {
return handleCollectionFetchError("cycle", userId, err);
}
const readings: WhoopMeasurementUpsert[] = [];
for (const c of records) {
for (const m of mapCycle(c)) {
readings.push({
type: m.type,
value: m.value,
unit: m.unit,
measuredAt: m.measuredAt,
externalId: `cycle:${c.id}:${m.fieldTag}`,
});
}
}
const imported = await upsertWhoopMeasurements(userId, readings);
await markResourceSynced(userId, "cycle");
return imported;
}