Last active
June 14, 2023 02:12
-
-
Save earlgreyxxx/ac2dc22f79e1356446b7881c67c82045 to your computer and use it in GitHub Desktop.
This file contains 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
// use Cache API and cache expire 2 weeks | |
async function cachedFetchJson(uri,seconds) | |
{ | |
const expire = seconds || (14 * 24 * 3600); | |
const today = Math.ceil(new Date().getTime() / 1000); | |
const cache = await caches.open('v1'); | |
let response = await cache.match(uri); | |
if(!response || ((parseInt(response.headers.get('cache-timestamp') || -1) + expire <= today))) | |
{ | |
await addex(cache,uri); | |
response = await cache.match(uri); | |
} | |
return response.json(); | |
} | |
// add cache cloned response | |
async function addex(cache,url) | |
{ | |
return fetch(url).then(async (response) => { | |
if (!response.ok) { | |
throw new TypeError("bad response status"); | |
} | |
const headers = new Headers(response.headers); | |
headers.append('Cache-Timestamp',Math.ceil(new Date().getTime() / 1000)); | |
const blob = await response.blob(); | |
return cache.put( | |
url, | |
new Response(blob, { | |
status: response.status, | |
statusText: "", | |
headers | |
}) | |
); | |
}); | |
} | |
// no using Cache API | |
async function fetchJson(uri) | |
{ | |
const response = await fetch(uri); | |
if(!response.ok) | |
throw new Error('invalid response') | |
return response.json(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment