diff --git a/src/api/Fees.js b/src/api/Fees.js index 21063c9d..7967f9a7 100644 --- a/src/api/Fees.js +++ b/src/api/Fees.js @@ -1,5 +1,6 @@ // @flow import invariant from 'invariant' +import LRU from 'lru-cache' import type { Currency } from '@ledgerhq/live-common/lib/types' import createCustomErrorClass from 'helpers/createCustomErrorClass' import { blockchainBaseURL } from './Ledger' @@ -11,10 +12,20 @@ export type Fees = { [_: string]: number, } +const cache = LRU({ + maxAge: 5 * 60 * 1000, +}) + export const getEstimatedFees = async (currency: Currency): Promise => { + const key = currency.id + let promise = cache.get(key) + if (promise) return promise.then(r => r.data) const baseURL = blockchainBaseURL(currency) invariant(baseURL, `Fees for ${currency.id} are not supported`) - const { data, status } = await network({ method: 'GET', url: `${baseURL}/fees` }) + promise = network({ method: 'GET', url: `${baseURL}/fees` }) + cache.set(key, promise) + const { data, status } = await promise + if (status < 200 || status >= 300) cache.del(key) if (data) { return data } diff --git a/src/components/SelectExchange.js b/src/components/SelectExchange.js index 93c76db9..7872e598 100644 --- a/src/components/SelectExchange.js +++ b/src/components/SelectExchange.js @@ -1,6 +1,7 @@ // @flow import React, { Component } from 'react' import { translate } from 'react-i18next' +import LRU from 'lru-cache' import type { Currency } from '@ledgerhq/live-common/lib/types' import type { Exchange } from '@ledgerhq/live-common/lib/countervalues/types' import logger from 'logger' @@ -10,6 +11,18 @@ import Text from 'components/base/Text' import CounterValues from 'helpers/countervalues' import type { T } from 'types/common' +const cache = LRU({ max: 100 }) + +const getExchanges = (from: Currency, to: Currency) => { + const key = `${from.ticker}_${to.ticker}` + let promise = cache.get(key) + if (promise) return promise + promise = CounterValues.fetchExchangesForPair(from, to) + promise.catch(() => cache.del(key)) // if it's a failure, we don't want to keep the cache + cache.set(key, promise) + return promise +} + class SelectExchange extends Component< { from: Currency, @@ -65,7 +78,7 @@ class SelectExchange extends Component< const { _loadId } = this const { from, to } = this.props try { - const exchanges = await CounterValues.fetchExchangesForPair(from, to) + const exchanges = await getExchanges(from, to) if (!this._unmounted && this._loadId === _loadId) { this.setState({ exchanges }) }