Skip to content

Instantly share code, notes, and snippets.

@abuseofnotation
Last active May 16, 2019 10:25
Show Gist options
  • Save abuseofnotation/ea33064e19470617179f57321e436107 to your computer and use it in GitHub Desktop.
Save abuseofnotation/ea33064e19470617179f57321e436107 to your computer and use it in GitHub Desktop.
A drop-in replacement for the JS `fetch` method which caches all GET requests. Supports an additional parameter `cachePeriod` allowing you to specify how recent should the response be.
const maxCachePeriod = 3000;
const cache = new Map();
setInterval(() => {
const now = +new Date();
cache.forEach((value, key, map) => {
if (now - value.time > maxCachePeriod) {
cache.delete(key);
}
});
}, maxCachePeriod);
const cachedFetch(url: string, config: HttpReqConfig, cachePeriod: number = maxCachePeriod): Promise<Response> {
if (config.method === 'get') {
const cacheResponse = cache.get(url);
if (cacheResponse !== undefined && +new Date() - cacheResponse.time < cachePeriod) {
// console.log('Returning from front-end cache ', url, ' from ', +new Date() - cacheResponse.time, ' millis ago');
return cacheResponse.response.then((response: Response) => response.clone());
} else {
const response = fetch(url, config);
cache.set(url, {
time: +new Date(),
response
});
return response.then((response) => response.clone());
}
} else {
return fetch(url, config);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment