Skip to content

Commit

Permalink
Fix SW for API calls by responding with network response first (#413)
Browse files Browse the repository at this point in the history
* Fix SW for API calls by responding with network response first

* Update package-lock.json

* Improve implementation
  • Loading branch information
Shailesh351 authored Sep 24, 2020
1 parent 7abe3f3 commit cd87e95
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
6 changes: 2 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 7 additions & 3 deletions public/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function handleAvatar(request, response) {
caches.open(version).then((cache) => cache.put(new Request(url), clonedResponse));
}

const fetchFromNetwork = (event) => {
const fetchFromNetwork = (event, cached) => {
const requestToFetch = event.request.clone();
return fetch(requestToFetch, { cache: 'reload' }).then((response) => {
const clonedResponse = response.clone();
Expand Down Expand Up @@ -57,7 +57,7 @@ const fetchFromNetwork = (event) => {
}
return response;
}).catch(() => {
if (hasHash(event.request.url)) { return caches.match(event.request.url); }
if (cached) { return cached; }
// If the request URL hasn't been served from cache and isn't sockjs we suppose it's HTML
if (!/\/sockjs\//.test(event.request.url)) { return caches.match(HTMLToCache); }
// Only for sockjs
Expand Down Expand Up @@ -106,9 +106,13 @@ self.addEventListener('fetch', (event) => {
const resourceType = cached.headers.get('content-type');
// We only return non css/js/html cached response e.g images
if (!hasHash(event.request.url) && !/text\/html/.test(resourceType)) {
// If API call try to respond with network response first
if (/\/api\//.test(event.request.url)) {
return fetchFromNetwork(event, cached);
}
// Refresh resources which are not(sound or assets)
if (!/sounds/.test(event.request.url) && !/assets/.test(event.request.url) && !/font/.test(event.request.url)) {
fetchFromNetwork(event);
fetchFromNetwork(event, cached);
}
return cached;
}
Expand Down

0 comments on commit cd87e95

Please sign in to comment.