You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.7 KiB
56 lines
1.7 KiB
4 years ago
|
import getFetchWithTimeout from '../../../shared/modules/fetch-with-timeout';
|
||
|
import { getStorageItem, setStorageItem } from './storage-helpers';
|
||
6 years ago
|
|
||
4 years ago
|
const fetchWithCache = async (
|
||
|
url,
|
||
|
fetchOptions = {},
|
||
|
{ cacheRefreshTime = 360000, timeout = 30000 } = {},
|
||
|
) => {
|
||
|
if (
|
||
|
fetchOptions.body ||
|
||
|
(fetchOptions.method && fetchOptions.method !== 'GET')
|
||
|
) {
|
||
4 years ago
|
throw new Error('fetchWithCache only supports GET requests');
|
||
5 years ago
|
}
|
||
5 years ago
|
if (!(fetchOptions.headers instanceof window.Headers)) {
|
||
4 years ago
|
fetchOptions.headers = new window.Headers(fetchOptions.headers);
|
||
5 years ago
|
}
|
||
|
if (
|
||
|
fetchOptions.headers.has('Content-Type') &&
|
||
|
fetchOptions.headers.get('Content-Type') !== 'application/json'
|
||
|
) {
|
||
4 years ago
|
throw new Error('fetchWithCache only supports JSON responses');
|
||
5 years ago
|
}
|
||
6 years ago
|
|
||
4 years ago
|
const currentTime = Date.now();
|
||
|
const cacheKey = `cachedFetch:${url}`;
|
||
|
const { cachedResponse, cachedTime } = (await getStorageItem(cacheKey)) || {};
|
||
5 years ago
|
if (cachedResponse && currentTime - cachedTime < cacheRefreshTime) {
|
||
4 years ago
|
return cachedResponse;
|
||
6 years ago
|
}
|
||
4 years ago
|
fetchOptions.headers.set('Content-Type', 'application/json');
|
||
|
const fetchWithTimeout = getFetchWithTimeout(timeout);
|
||
4 years ago
|
const response = await fetchWithTimeout(url, {
|
||
4 years ago
|
referrerPolicy: 'no-referrer-when-downgrade',
|
||
|
body: null,
|
||
|
method: 'GET',
|
||
|
mode: 'cors',
|
||
|
...fetchOptions,
|
||
4 years ago
|
});
|
||
4 years ago
|
if (!response.ok) {
|
||
4 years ago
|
throw new Error(
|
||
|
`Fetch failed with status '${response.status}': '${response.statusText}'`,
|
||
4 years ago
|
);
|
||
4 years ago
|
}
|
||
4 years ago
|
const responseJson = await response.json();
|
||
4 years ago
|
const cacheEntry = {
|
||
|
cachedResponse: responseJson,
|
||
|
cachedTime: currentTime,
|
||
4 years ago
|
};
|
||
4 years ago
|
|
||
4 years ago
|
await setStorageItem(cacheKey, cacheEntry);
|
||
|
return responseJson;
|
||
|
};
|
||
5 years ago
|
|
||
4 years ago
|
export default fetchWithCache;
|