Fixed db resync.

This commit is contained in:
Pen Anderson 2026-03-10 14:24:51 -05:00
parent 1eb6a99ff6
commit da5f3524fa
2 changed files with 45 additions and 5 deletions

View file

@ -4,10 +4,36 @@ import { api } from './api.js'
let syncing = false
let sseSource = null
async function checkBuildChanged() {
try {
const res = await fetch('/api/version')
const { build } = await res.json()
if (!build) return
const stored = await db.meta.get('build')
if (!stored || stored.value !== build) {
await db.transaction('rw',
[db.meta, db.event, db.participants, db.tickets, db.departments, db.volunteers, db.shifts, db.volunteer_shifts],
async () => {
await db.meta.clear()
await db.event.clear()
await db.participants.clear()
await db.tickets.clear()
await db.departments.clear()
await db.volunteers.clear()
await db.shifts.clear()
await db.volunteer_shifts.clear()
}
)
}
await db.meta.put({ key: 'build', value: build })
} catch {}
}
export async function syncPull() {
if (syncing) return
syncing = true
try {
await checkBuildChanged()
const since = await getLastSync()
const data = await api.sync.pull(since)
@ -51,7 +77,7 @@ export async function syncPull() {
}
)
await setLastSync(data.server_time)
if (data.server_time) await setLastSync(data.server_time)
return true
} catch (err) {
console.warn('Sync pull failed:', err.message)
@ -97,7 +123,7 @@ export function startSSE(onEvent) {
syncPull()
}, 5000)
}
})
}).catch(() => {})
}
connect()
@ -108,18 +134,23 @@ export function stopSSE() {
sseSource = null
}
// Poll for sync when online, with exponential backoff on failure
let syncInterval = null
let onlineHandler = null
export function startSyncLoop(intervalMs = 30000) {
if (syncInterval) return
syncInterval = setInterval(() => {
if (navigator.onLine) syncPull()
}, intervalMs)
window.addEventListener('online', () => syncPull())
onlineHandler = () => syncPull()
window.addEventListener('online', onlineHandler)
}
export function stopSyncLoop() {
clearInterval(syncInterval)
syncInterval = null
if (onlineHandler) {
window.removeEventListener('online', onlineHandler)
onlineHandler = null
}
}