({
forceRefresh = false,
key,
legacyFields = [],
load,
priority = FOREGROUND_PRIORITY,
})
| 175 | } |
| 176 | |
| 177 | export async function loadCachedValue({ |
| 178 | forceRefresh = false, |
| 179 | key, |
| 180 | legacyFields = [], |
| 181 | load, |
| 182 | priority = FOREGROUND_PRIORITY, |
| 183 | }) { |
| 184 | const isBackground = priority === BACKGROUND_PRIORITY; |
| 185 | const requestEpoch = cacheEpoch; |
| 186 | const entry = await readCacheEntry(key, {legacyFields, requestEpoch}); |
| 187 | if (requestEpoch !== cacheEpoch) { |
| 188 | return entry?.value; |
| 189 | } |
| 190 | if (!isCacheEntryExpired(entry, forceRefresh)) { |
| 191 | return entry.value; |
| 192 | } |
| 193 | if (isBackground && foregroundRequests.has(key)) { |
| 194 | return entry?.value; |
| 195 | } |
| 196 | const loadMap = isBackground ? backgroundLoads : foregroundLoads; |
| 197 | if (loadMap.has(key)) { |
| 198 | return loadMap.get(key); |
| 199 | } |
| 200 | |
| 201 | const request = beginCacheRequests([key], priority, requestEpoch); |
| 202 | if (request.keys.length === 0) { |
| 203 | return entry?.value; |
| 204 | } |
| 205 | const pendingLoad = (async () => { |
| 206 | try { |
| 207 | const value = await load(); |
| 208 | const cacheWrite = writeCacheValue(key, value, { |
| 209 | requestEpoch: request.epoch, |
| 210 | requestVersion: request.versionFor(key), |
| 211 | }); |
| 212 | if (isBackground) { |
| 213 | await cacheWrite; |
| 214 | } else { |
| 215 | void cacheWrite.catch(() => { |
| 216 | }); |
| 217 | } |
| 218 | return value; |
| 219 | } finally { |
| 220 | request.release(); |
| 221 | } |
| 222 | })(); |
| 223 | loadMap.set(key, pendingLoad); |
| 224 | return pendingLoad.finally(() => { |
| 225 | if (loadMap.get(key) === pendingLoad) { |
| 226 | loadMap.delete(key); |
| 227 | } |
| 228 | }); |
| 229 | } |
no test coverage detected