Skip to content

Instantly share code, notes, and snippets.

@paitonic
Last active August 21, 2021 13:30
Show Gist options
  • Save paitonic/6cc11223464ee42c258b090b5632b3e4 to your computer and use it in GitHub Desktop.
Save paitonic/6cc11223464ee42c258b090b5632b3e4 to your computer and use it in GitHub Desktop.
cache-api
// Example 1 - fetch()
function fetchExample() {
appCacheName = 'my-app';
async function fetchData(url) {
// remove from cache
// const keys = await caches.keys();
// for (const key of keys) {
// console.log('deleting: ', key)
// caches.delete(key);
// }
request = new Request(url)
const cacheStorage = await caches.open(appCacheName);
const cached = await cacheStorage.match(request);
if (cached) {
console.log(`${url} found in cache`);
return cached.json();
}
console.log(`${url} not found in cache`);
const response = await fetch(request);
await cacheStorage.put(request, response.clone());
return response.json();
}
postsURL = 'https://jsonplaceholder.typicode.com/posts';
usersURL = 'https://jsonplaceholder.typicode.com/users';
fetchData(usersURL).then(response => {
console.log('response: ', response);
})
}
// Example 2 - axios
// Somewhat awkward way to use Cache API with axios.
// Cache API works with Request and Response objects (see fetch).
// This snippet creates fake request object that will serve as cache key.
// The response from axios will be stringified and stored as cache value.
// Is there a better way to do this? Note that you should take in account situation where axios response interceptors defined.
function axiosExample() {
appCacheName = 'my-app';
async function fetchData(url) {
// remove from cache
// const keys = await caches.keys();
// for (const key of keys) {
// console.log('deleting: ', key)
// caches.delete(key);
// }
request = new Request(url);
const cacheStorage = await caches.open(appCacheName);
const cached = await cacheStorage.match(request);
if (cached) {
console.log(`${url} found in cache`);
return cached.json(); // TODO
}
console.log(`${url} not found in cache`);
// feed URL from Request object to axios
const response = await axios.get(request.url);
// wasteful encoding. axios already took care of this.
const r = new Response(JSON.stringify(response.data));
await cacheStorage.put(request, r.clone());
return r.json();
}
postsURL = 'https://jsonplaceholder.typicode.com/posts';
usersURL = 'https://jsonplaceholder.typicode.com/users';
fetchData(usersURL).then(response => {
console.log('response: ', response);
})
}
// fetchExample();
axiosExample();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment