Skip to content

Commit

Permalink
Adds fetchWithCache to guard against unnecessary API calls
Browse files Browse the repository at this point in the history
  • Loading branch information
danjm authored and whymarrh committed May 7, 2019
1 parent 3f2889b commit 891fbb7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
22 changes: 22 additions & 0 deletions ui/app/helpers/utils/fetch-with-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {
loadLocalStorageData,
saveLocalStorageData,
} from '../../../lib/local-storage-helpers'

export default function fetchWithCache (url, opts, cacheRefreshTime = 360000) {
const currentTime = Date.now()
const cachedFetch = loadLocalStorageData('cachedFetch') || {}
const { cachedUrl, cachedTime } = cachedFetch[url] || {}
if (cachedUrl && currentTime - cachedTime < 360000) {
return cachedFetch[url]
} else {
cachedFetch[url] = { cachedUrl: url, cachedTime: currentTime }
saveLocalStorageData(cachedFetch, 'cachedFetch')
return fetch(url, {
referrerPolicy: 'no-referrer-when-downgrade',
body: null,
method: 'GET',
mode: 'cors',
})
}
}
3 changes: 2 additions & 1 deletion ui/app/helpers/utils/transactions.util.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
TRANSACTION_TYPE_CANCEL,
TRANSACTION_STATUS_CONFIRMED,
} from '../../../../app/scripts/controllers/transactions/enums'
import fetchWithCache from './fetch-with-cache'

import {
TOKEN_METHOD_TRANSFER,
Expand All @@ -31,7 +32,7 @@ export function getTokenData (data = '') {
}

async function getMethodFrom4Byte (fourBytePrefix) {
const fourByteResponse = (await fetch(`https://www.4byte.directory/api/v1/signatures/?hex_signature=${fourBytePrefix}`, {
const fourByteResponse = (await fetchWithCache(`https://www.4byte.directory/api/v1/signatures/?hex_signature=${fourBytePrefix}`, {
referrerPolicy: 'no-referrer-when-downgrade',
body: null,
method: 'GET',
Expand Down

0 comments on commit 891fbb7

Please sign in to comment.