Last active
May 16, 2019 10:25
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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