Skip to content

Instantly share code, notes, and snippets.

@jitheshkt
Last active November 19, 2021 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jitheshkt/72df53c3630b6e7f0eba4a8963103654 to your computer and use it in GitHub Desktop.
Save jitheshkt/72df53c3630b6e7f0eba4a8963103654 to your computer and use it in GitHub Desktop.
Caching REST API response to browser HTTP cache
let controller = new AbortController();
const trans = await fetch('/api/something.json',{cache: "only-if-cached", mode: "same-origin", signal: controller.signal}).then(res => {
const date = res.headers.get("date"), dt = date ? new Date(date).getTime() : 0;
console.log('hit cache');
if (dt < (Date.now() - 100000)) {
console.log('refresh time');
// if older than 1 minute
controller.abort()
controller = new AbortController();
return fetch('/api/something.json', {cache: "reload", mode: "same-origin", signal: controller.signal});
}
return res;
}).then(async (response) => {
let data = await response.json();
return data;
});
//Do what ever you want with the response using trans variable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment