mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
48b1e879d2
Holding later queued writes behind a parked one only ordered writes that were in the queue. Online, the repos send an edit straight to the server, so an edit made while an older write to the same visit, tour or driving settings was backing off or parked landed first, and Try again (or the next flush) then replayed the older write over it. Those writes carry no version token, so nothing refused the stale replay. The repos of visits, day clears, tours and driving settings now ask the queue before an online write. While an older write to the same entity is pending, in flight, parked or a conflict, the new write is queued too, with the same optimistic Dexie write as offline, and a flush is started so it goes out as soon as the one ahead of it does. When the driving settings left the cache since the older write, they are read in first. Places and packing items keep their direct online path: they send the base token, so a stale replay is refused with a 409 and becomes a conflict. What this does not cover, and the docs now say so: a collaborator's change to a token-less entity is overwritten by the retried write, as by any replayed offline write of those resources, and the planner's two time edits that call the API directly are not held. The wording of the parking commit also named budget items, which never go through the queue.
60 lines
3.4 KiB
TypeScript
60 lines
3.4 KiB
TypeScript
import { roadtripPreferencesResponseSchema, roadtripPreferencesUpdateSchema, type RoadtripPreferences } from '@trek/shared'
|
|
import { apiClient } from '../api/client'
|
|
import { offlineDb } from '../db/offlineDb'
|
|
import { generateUUID, mutationQueue } from '../sync/mutationQueue'
|
|
import { isEffectivelyOffline } from '../sync/networkMode'
|
|
import { onlineThenCache } from './withOfflineFallback'
|
|
|
|
export async function cachedRoadtripPreferences(tripId: number, excludeMutation?: string): Promise<RoadtripPreferences> {
|
|
const cached = await offlineDb.roadtripPreferences.get(tripId)
|
|
if (!cached) throw new Error('Driving settings are not available offline.')
|
|
const pending = await offlineDb.mutationQueue.where('tripId').equals(tripId).sortBy('createdAt')
|
|
return pending.reduce((preferences, mutation) => {
|
|
if (mutation.resource !== 'roadtripPreferences' || mutation.id === excludeMutation || !['pending', 'syncing'].includes(mutation.status)) return preferences
|
|
return { ...preferences, ...roadtripPreferencesUpdateSchema.parse(mutation.body) }
|
|
}, cached.preferences)
|
|
}
|
|
|
|
const writes = new Map<number, Promise<RoadtripPreferences>>()
|
|
|
|
export const roadtripPreferencesRepo = {
|
|
async read(tripId: number): Promise<RoadtripPreferences> {
|
|
const cacheName = offlineDb.name
|
|
return onlineThenCache(async () => {
|
|
const fetched = await apiClient.get(`/trips/${tripId}/roadtrip/preferences`)
|
|
if (offlineDb.name !== cacheName) throw new Error('Account changed.')
|
|
const saved = roadtripPreferencesResponseSchema.parse(fetched.data)
|
|
await offlineDb.roadtripPreferences.put(saved)
|
|
return cachedRoadtripPreferences(tripId)
|
|
}, () => cachedRoadtripPreferences(tripId))
|
|
},
|
|
|
|
update(tripId: number, patch: RoadtripPreferences): Promise<RoadtripPreferences> {
|
|
const cacheName = offlineDb.name
|
|
const save = (writes.get(tripId) ?? Promise.resolve({})).catch(() => ({})).then(async () => {
|
|
if (offlineDb.name !== cacheName) throw new Error('Account changed.')
|
|
const validated = roadtripPreferencesUpdateSchema.parse(patch)
|
|
if (!(await mutationQueue.mustQueue('roadtripPreferences', tripId))) {
|
|
const saved = await apiClient.put(`/trips/${tripId}/roadtrip/preferences`, validated)
|
|
if (offlineDb.name !== cacheName) throw new Error('Account changed.')
|
|
await offlineDb.roadtripPreferences.put(roadtripPreferencesResponseSchema.parse(saved.data))
|
|
} else {
|
|
// Online and behind an older queued write: the trip may have left the
|
|
// cache since that write was made, so read the settings in first.
|
|
if (!isEffectivelyOffline() && !(await offlineDb.roadtripPreferences.get(tripId))) await roadtripPreferencesRepo.read(tripId)
|
|
const next = { ...await cachedRoadtripPreferences(tripId), ...validated }
|
|
if (next.roadtrip_day_start && next.roadtrip_day_end && next.roadtrip_day_end <= next.roadtrip_day_start) throw new Error('Day end must be later than day start.')
|
|
await mutationQueue.enqueue({
|
|
id: generateUUID(), tripId, method: 'PUT', url: `/trips/${tripId}/roadtrip/preferences`,
|
|
body: validated, resource: 'roadtripPreferences', entityId: tripId,
|
|
})
|
|
mutationQueue.sendSoon()
|
|
}
|
|
return cachedRoadtripPreferences(tripId)
|
|
})
|
|
writes.set(tripId, save)
|
|
void save.finally(() => { if (writes.get(tripId) === save) writes.delete(tripId) }).catch(() => {})
|
|
return save
|
|
},
|
|
}
|