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.
57 lines
1.7 KiB
57 lines
1.7 KiB
2 years ago
|
import { MINUTE, SECOND } from '../constants/time';
|
||
|
import getFetchWithTimeout from '../modules/fetch-with-timeout';
|
||
4 years ago
|
import { getStorageItem, setStorageItem } from './storage-helpers';
|
||
6 years ago
|
|
||
4 years ago
|
const fetchWithCache = async (
|
||
|
url,
|
||
|
fetchOptions = {},
|
||
4 years ago
|
{ cacheRefreshTime = MINUTE * 6, timeout = SECOND * 30 } = {},
|
||
4 years ago
|
) => {
|
||
|
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;
|