2019-06-18 14:17:14 +02:00
|
|
|
import {
|
|
|
|
loadLocalStorageData,
|
|
|
|
saveLocalStorageData,
|
|
|
|
} from '../../../lib/local-storage-helpers'
|
2019-09-04 22:00:11 +02:00
|
|
|
import fetchWithTimeout from '../../../../app/scripts/lib/fetch-with-timeout'
|
2019-06-18 14:17:14 +02:00
|
|
|
|
2019-09-04 21:10:23 +02:00
|
|
|
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 Headers)) {
|
|
|
|
fetchOptions.headers = new Headers(fetchOptions.headers)
|
|
|
|
}
|
|
|
|
if (
|
|
|
|
fetchOptions.headers &&
|
|
|
|
fetchOptions.headers.has('Content-Type') &&
|
|
|
|
fetchOptions.headers.get('Content-Type') !== 'application/json'
|
|
|
|
) {
|
|
|
|
throw new Error('fetchWithCache only supports JSON responses')
|
|
|
|
}
|
2019-06-18 14:17:14 +02:00
|
|
|
|
|
|
|
const currentTime = Date.now()
|
|
|
|
const cachedFetch = loadLocalStorageData('cachedFetch') || {}
|
2019-09-04 21:10:23 +02:00
|
|
|
const { cachedResponse, cachedTime } = cachedFetch[url] || {}
|
|
|
|
if (cachedResponse && currentTime - cachedTime < cacheRefreshTime) {
|
|
|
|
return cachedResponse
|
2019-06-18 14:17:14 +02:00
|
|
|
} else {
|
2019-09-04 21:10:23 +02:00
|
|
|
fetchOptions.headers.set('Content-Type', 'application/json')
|
|
|
|
const _fetch = timeout ?
|
|
|
|
fetchWithTimeout({ timeout }) :
|
|
|
|
fetch
|
|
|
|
const response = await _fetch(url, {
|
2019-06-18 14:17:14 +02:00
|
|
|
referrerPolicy: 'no-referrer-when-downgrade',
|
|
|
|
body: null,
|
|
|
|
method: 'GET',
|
|
|
|
mode: 'cors',
|
2019-09-04 21:10:23 +02:00
|
|
|
...fetchOptions,
|
2019-06-18 14:17:14 +02:00
|
|
|
})
|
2019-09-04 21:10:23 +02:00
|
|
|
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,
|
|
|
|
}
|
|
|
|
cachedFetch[url] = cacheEntry
|
|
|
|
saveLocalStorageData(cachedFetch, 'cachedFetch')
|
|
|
|
return responseJson
|
2019-06-18 14:17:14 +02:00
|
|
|
}
|
|
|
|
}
|
2019-09-04 21:10:23 +02:00
|
|
|
|
|
|
|
export default fetchWithCache
|