Browse Source

Merge pull request #633 from gre/lru-cache-on-selectexchange

add a cache on SelectExchange & getEstimatedFees
master
Meriadec Pillet 7 years ago
committed by GitHub
parent
commit
7db2c0de23
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 13
      src/api/Fees.js
  2. 15
      src/components/SelectExchange.js

13
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<Fees> => {
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
}

15
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 })
}

Loading…
Cancel
Save