Last active
November 19, 2021 18:01
-
-
Save jitheshkt/72df53c3630b6e7f0eba4a8963103654 to your computer and use it in GitHub Desktop.
Caching REST API response to browser HTTP cache
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
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