1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-24 02:58:09 +01:00
metamask-extension/ui/app/helpers/utils/fetch-with-cache.js
Erik Marks 7159dd6867
Fetch with a timeout everywhere (#10101)
* Use fetchWithTimeout everywhere
* Memoize getFetchWithTimeout
* Require specified timeout
2021-01-19 08:41:57 -08:00

56 lines
1.7 KiB
JavaScript

import { getStorageItem, setStorageItem } from '../../../lib/storage-helpers'
import getFetchWithTimeout from '../../../../shared/modules/fetch-with-timeout'
const fetchWithCache = async (
url,
fetchOptions = {},
{ cacheRefreshTime = 360000, timeout = 30000 } = {},
) => {
if (
fetchOptions.body ||
(fetchOptions.method && fetchOptions.method !== 'GET')
) {
throw new Error('fetchWithCache only supports GET requests')
}
if (!(fetchOptions.headers instanceof window.Headers)) {
fetchOptions.headers = new window.Headers(fetchOptions.headers)
}
if (
fetchOptions.headers.has('Content-Type') &&
fetchOptions.headers.get('Content-Type') !== 'application/json'
) {
throw new Error('fetchWithCache only supports JSON responses')
}
const currentTime = Date.now()
const cacheKey = `cachedFetch:${url}`
const { cachedResponse, cachedTime } = (await getStorageItem(cacheKey)) || {}
if (cachedResponse && currentTime - cachedTime < cacheRefreshTime) {
return cachedResponse
}
fetchOptions.headers.set('Content-Type', 'application/json')
const fetchWithTimeout = getFetchWithTimeout(timeout)
const response = await fetchWithTimeout(url, {
referrerPolicy: 'no-referrer-when-downgrade',
body: null,
method: 'GET',
mode: 'cors',
...fetchOptions,
})
if (!response.ok) {
throw new Error(
`Fetch failed with status '${response.status}': '${response.statusText}'`,
)
}
const responseJson = await response.json()
const cacheEntry = {
cachedResponse: responseJson,
cachedTime: currentTime,
}
await setStorageItem(cacheKey, cacheEntry)
return responseJson
}
export default fetchWithCache