Compare commits

..

View file

@ -112,31 +112,48 @@ export async function syncAll(): Promise<SyncResult> {
if (remote.length > 0) { if (remote.length > 0) {
const local = await getAllMeasurementsForSync() const local = await getAllMeasurementsForSync()
const merged = mergeMeasurements(local, remote)
const localMap = new Map(local.map(m => [m.id, m])) const localMap = new Map(local.map(m => [m.id, m]))
for (const m of merged) { for (const r of remote) {
if (m.deletedAt) { const localRec = localMap.get(r.id)
await removeMeasurement(m.id) const isDeleted = !!(r as any).deleted
const localRec = localMap.get(m.id)
if (localRec && !localRec.deletedAt) {
pulled++
}
} else {
const localRec = localMap.get(m.id)
const isNew = !localRec
const isUpdated =
localRec &&
new Date(m.updatedAt).getTime() !==
new Date(localRec.updatedAt).getTime()
if (isNew || isUpdated) { if (isDeleted) {
await upsertMeasurement(m) if (localRec) {
await updateSyncStatus(m.id, 'synced') if (
localRec.syncStatus === 'pending' ||
localRec.syncStatus === 'pending-delete'
) {
continue
}
await removeMeasurement(r.id)
deleted++
}
continue
}
const localIsPending =
localRec?.syncStatus === 'pending' ||
localRec?.syncStatus === 'pending-delete'
if (localIsPending) {
continue
}
if (localRec) {
if (new Date(r.updatedAt) > new Date(localRec.updatedAt)) {
const record = { ...r, deletedAt: (r as any).deletedAt || undefined } as Measurement
await upsertMeasurement(record)
await updateSyncStatus(r.id, 'synced')
pulled++ pulled++
} }
continue
} }
const record = { ...r, deletedAt: (r as any).deletedAt || undefined } as Measurement
await upsertMeasurement(record)
await updateSyncStatus(r.id, 'synced')
pulled++
} }
} }