Skip to content

Commit 1cb0304

Browse files
committed
Only add or update cached pairs if they successfully return a rate
1 parent 6cbf6f5 commit 1cb0304

File tree

1 file changed

+55
-2
lines changed

1 file changed

+55
-2
lines changed

src/actions/ExchangeRateActions.ts

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -408,11 +408,64 @@ async function fetchExchangeRates(
408408
})
409409
await Promise.allSettled(promises)
410410

411+
// Merge successful rate responses into the pair cache
412+
const cryptoPairCache = [...(exchangeRateCache?.cryptoPairs ?? [])]
413+
const fiatPairCache = [...(exchangeRateCache?.fiatPairs ?? [])]
414+
const pairCacheExpiration = Date.now() + ONE_MONTH
415+
for (const [pluginId, tokenObj] of Object.entries(rates.crypto)) {
416+
for (const [tokenId, rateObj] of Object.entries(tokenObj)) {
417+
for (const targetFiat of Object.keys(rateObj)) {
418+
const cryptoPairIndex = cryptoPairCache.findIndex(
419+
pair =>
420+
pair.asset.pluginId === pluginId &&
421+
pair.asset.tokenId === tokenId &&
422+
pair.targetFiat === targetFiat
423+
)
424+
if (cryptoPairIndex === -1) {
425+
cryptoPairCache.push({
426+
asset: { pluginId, tokenId },
427+
targetFiat,
428+
isoDate: undefined,
429+
expiration: pairCacheExpiration
430+
})
431+
} else {
432+
cryptoPairCache[cryptoPairIndex] = {
433+
asset: { pluginId, tokenId },
434+
targetFiat,
435+
isoDate: undefined,
436+
expiration: pairCacheExpiration
437+
}
438+
}
439+
}
440+
}
441+
}
442+
for (const [fiatCode, fiatObj] of Object.entries(rates.fiat)) {
443+
for (const targetFiat of Object.keys(fiatObj)) {
444+
const fiatPairIndex = fiatPairCache.findIndex(
445+
pair => pair.fiatCode === fiatCode && pair.targetFiat === targetFiat
446+
)
447+
if (fiatPairIndex === -1) {
448+
fiatPairCache.push({
449+
fiatCode,
450+
targetFiat,
451+
isoDate: undefined,
452+
expiration: pairCacheExpiration
453+
})
454+
} else {
455+
fiatPairCache[fiatPairIndex] = {
456+
fiatCode,
457+
targetFiat,
458+
isoDate: undefined,
459+
expiration: pairCacheExpiration
460+
}
461+
}
462+
}
463+
}
411464
// Update the in-memory cache:
412465
exchangeRateCache = {
413466
rates,
414-
cryptoPairs: Array.from(cryptoPairMap.values()),
415-
fiatPairs: Array.from(fiatPairMap.values())
467+
cryptoPairs: cryptoPairCache,
468+
fiatPairs: fiatPairCache
416469
}
417470

418471
// Write the cache to disk:

0 commit comments

Comments
 (0)