Skip to content

Instantly share code, notes, and snippets.

@oilsinwater
Created September 9, 2018 05:10
Show Gist options
  • Save oilsinwater/8d87fd1f82e4a32428b2ada782c6d292 to your computer and use it in GitHub Desktop.
Save oilsinwater/8d87fd1f82e4a32428b2ada782c6d292 to your computer and use it in GitHub Desktop.
Sw
const staticCache = 'static-restaurant-1';
//open cache and add specified files to it
const requiredFiles = [
'/sw.js',
'/index.html',
'/restaurant.html',
'/js/dbhelper.js',
'/js/main.js',
'/js/register.js',
'/js/idb.js',
'/js/restaurant_info.js',
'/css/home.css',
'/css/review.css',
'/data/restaurants.json',
'/restaurant.html?id=1',
'/restaurant.html?id=2',
'/restaurant.html?id=3',
'/restaurant.html?id=4',
'/restaurant.html?id=5',
'/restaurant.html?id=6',
'/restaurant.html?id=7',
'/restaurant.html?id=8',
'/restaurant.html?id=9',
'/restaurant.html?id=10'
];
const dbPromise = idb.open('restaurant-db', 1, upgradeDB => {
switch (upgradeDB.oldVersion) {
case 0:
upgradeDB.createObjectStore('restaurants'), { keyPath: 'id' };
}
});
self.addEventListener('install', event => {
event.waitUntil(
caches
.open(staticCache)
.then(cache => {
return cache.addAll(requiredFiles);
})
.catch(error => {
console.log(`Caches open failed ${error}`);
})
.then(() => {
return self.skipWaiting();
})
);
});
// return file from server, if it is not in the cache
self.addEventListener('fetch', event => {
let cacheRequest = event.request;
let cacheUrlObj = new URL(even.request.url);
if (event.request.url.indexOf('restaurant.html') > -1) {
const cacheURL = 'restaurant.html';
cacheRequest = new Request(cacheUrl);
}
// Requests going to the API get handled separately from those going to other destinations
const checkURL = new URL(event.request.url);
if (checkURL.port === '1337') {
const parts = checkURL.pathname.split('/');
const id =
parts[parts.length - 1] === 'restaurants'
? '-1'
: parts[parts.length - 1];
handleAJAXEvent(event, id);
} else {
handleNonAJAXEvent(event, cacheRequest);
}
});
const handleAJAXEvent = (event, id) => {
// checking the IndexedDB to see if the JSON for the API
event.respondWith(
dbPromise
.then(db => {
return db
.transaction('restaurants')
.objectStore('restaurants')
.get(id);
})
.then(data => {
return (
(data && data.data) ||
fetch(event.request)
.then(fetchResponse => fetchResponse.json())
.then(json => {
return dbPromise.then(db => {
const tx = db.transaction('restaurants', 'readwrite');
tx.objectStore('restaurants').put({
id: id,
data: json
});
return json;
});
})
);
})
.then(finalResponse => {
return new Response(JSON.stringify(finalResponse));
})
.catch(error => {
return new Response(JSON.stringify(finalResponse));
})
.catch(error => {
return new Response('Error fetching data', { status: 500 });
})
);
};
const handleNonAJAXEvent = (event, cacheRequest) => {
// Check if HTML has previously been cached.
// If, so return the response from the cache.
// If not, fetch the request, cache it, and return it
event.respondWith(
caches.match(cacheRequest).then(response => {
return (
response ||
fetch(event.request)
.then(fetchResponse => {
return caches.open(cacheID).then(cache => {
cache.put(event.request, fetchResponse.clonse());
return fetchResponse;
});
})
.catch(error => {
if (event.request.url.indexOf('.jpg') > -1) {
return caches.match('/img/offline.png');
}
return new Response('Not connected to the internet', {
status: 404,
statusText: 'No internet connection'
});
})
);
})
);
};
// self.addEventListener("fetch", event => {
// event.respondWith(
// caches
// .match(event.request)
// .then(response => {
// return (
// response ||
// fetch(event.request).then(fetchResponse => {
// return caches.open(staticCache).then(cache => {
// cache.put(event.request, fetchResponse.clone());
// return fetchResponse;
// });
// })
// );
// })
// .catch(error => {
// if (event.request.url.includes(".jpg")) {
// return caches.match("./img/unaltered/offline.png");
// }
// return new Response("Not connected to the internet", {
// status: 404,
// statusText: "Not connected to the internet"
// });
// })
// );
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment