Skip to content
This repository has been archived by the owner on Feb 13, 2024. It is now read-only.

Build a PWA using Workbox - Handle invalid responses needs getCacheKeyForURL #20

Open
kaplan81 opened this issue Jun 25, 2019 · 1 comment

Comments

@kaplan81
Copy link

kaplan81 commented Jun 25, 2019

Hi,

By following your lab I have noticed the registration of the route for articles that uses the NetworkFirst is developed wrong for the latest version of Workbox libraries.

In first place we need to use the new operator for NetworkFirst as a construct and not for networkFirst as a property.

Then we handle the response for both the case when there is a response but the page is unknown (404) and when there is no response from the server because we are offline. In the latter we need to handle this not within the Promise.prototype.then() method but within the Promise.prototype.catch() method.

And in both cases we need to use workbox.precaching.getCacheKeyForURL() method in order to get the correct key for caches.match().

The code looks like this:

const articleHandler = new workbox.strategies.NetworkFirst({
    cacheName: 'articles-cache',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 50
      })
    ]
  });

workbox.routing.registerRoute(/(.*)article(.*)\.html/, args => {
    return articleHandler
      .handle(args)
      .then(response => {
        if (response.status === 404) {
          const pageNotFoundKey = workbox.precaching.getCacheKeyForURL('pages/404.html');

          return caches.match(pageNotFoundKey);
        }
        return response;
      })
      .catch(error => {
        // The strategy could not generate a response for this URL.
        const pageOfflineKey = workbox.precaching.getCacheKeyForURL('pages/offline.html');

        return caches.match(pageOfflineKey);
      });
  });

Please check it out.

@DavidScales
Copy link
Contributor

Hi kaplan81, sorry for the slow reply! This lab isn't up to date with the latest version of Workbox. But it is open source and PR's are welcome 😉

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants