mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
fix(withings): key sleep re-sync on the stable externalId, not the shifting measuredAt
With measuredAt now stamped at the segment END, a night that Withings re-aggregates between syncs shifts its enddate, so the measuredAt-keyed lookup missed the prior row and the create then collided with the unique externalId — leaving the night stuck at its stale value. Key the lookup on the stable externalId and refresh value, measuredAt and stage on update. Caught by the withings-sleep-sync integration test against real Postgres.
This commit is contained in:
1 parent
78f0e067b5
commit
cbd5c2ba6f
2 files changed
+15
-4
No files matched your search
@@ -240,9 +240,15 @@ describe("syncUserSleep — segment writes + idempotency", () => {
|
||||
const imported = await syncUserSleep("user-1");
|
||||
expect(imported).toBe(1);
|
||||
expect(prisma.measurement.create).not.toHaveBeenCalled();
|
||||
// Re-sync keys on the stable externalId and refreshes value, the
|
||||
// END-stamped measuredAt (enddate may shift) and the stage.
|
||||
expect(prisma.measurement.update).toHaveBeenCalledWith({
|
||||
where: { id: "row-1" },
|
||||
data: { value: 60 },
|
||||
data: {
|
||||
value: 60,
|
||||
measuredAt: new Date(1715003600 * 1000),
|
||||
sleepStage: "DEEP",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -275,20 +275,25 @@ export async function syncUserSleep(
|
||||
const externalId = `withings:sleep:${userId}:${segment.id ?? "no-id"}:${segmentIndex}`;
|
||||
|
||||
try {
|
||||
// Key the re-sync lookup on the STABLE `externalId` (segment id +
|
||||
// index), not `measuredAt`. Withings re-aggregates a night between
|
||||
// syncs, so a segment's `enddate` — and therefore its END-stamped
|
||||
// `measuredAt` — shifts; keying on `measuredAt` would miss the prior
|
||||
// row and then collide with the unique `externalId`, leaving the night
|
||||
// stuck at the stale value. Update both `value` and `measuredAt`.
|
||||
const existing = await prisma.measurement.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
type: SLEEP_TYPE,
|
||||
measuredAt,
|
||||
source: "WITHINGS",
|
||||
sleepStage: stage,
|
||||
externalId,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (existing) {
|
||||
await prisma.measurement.update({
|
||||
where: { id: existing.id },
|
||||
data: { value: minutes },
|
||||
data: { value: minutes, measuredAt, sleepStage: stage },
|
||||
});
|
||||
} else {
|
||||
await prisma.measurement.create({
|
||||
|
||||
Reference in new issue
Block a user