pinafore/src/routes/_utils/sync.js

41 lines
1.4 KiB
JavaScript
Raw Normal View History

// Hit both the cache and the network, setting state for the cached version first,
// then the network version (as it's assumed to be fresher). Also update the db afterwards.
2018-02-08 22:29:29 -08:00
export async function cacheFirstUpdateAfter (networkFetcher, dbFetcher, dbUpdater, stateSetter) {
2019-08-03 13:49:37 -07:00
const networkPromise = networkFetcher() // kick off network request immediately
let dbResponse
try {
dbResponse = await dbFetcher()
} catch (err) {
console.error('ignored DB error', err)
} finally {
if (dbResponse) {
stateSetter(dbResponse)
}
2019-08-03 13:49:37 -07:00
const fetchAndUpdatePromise = networkPromise.then(networkResponse => {
/* no await */ dbUpdater(networkResponse)
stateSetter(networkResponse)
})
if (!dbResponse) { // no cached result available, await the network
await fetchAndUpdatePromise
}
}
2018-02-08 22:29:29 -08:00
}
// Try the cache first. If we get a hit, set the state and do nothing. If we don't get a cache hit,
// then go to the network, update the cache, and set the state.
export async function cacheFirstUpdateOnlyIfNotInCache (networkFetcher, dbFetcher, dbUpdater, stateSetter) {
let dbResponse
try {
dbResponse = await dbFetcher()
} catch (err) {
console.error('ignored DB error', err)
}
if (dbResponse) {
stateSetter(dbResponse)
} else {
const networkResponse = await networkFetcher()
/* no await */ dbUpdater(networkResponse)
stateSetter(networkResponse)
}
}