Skip to content

Instantly share code, notes, and snippets.

@earlgreyxxx
Last active June 14, 2023 02:12
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 earlgreyxxx/ac2dc22f79e1356446b7881c67c82045 to your computer and use it in GitHub Desktop.
Save earlgreyxxx/ac2dc22f79e1356446b7881c67c82045 to your computer and use it in GitHub Desktop.
// 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