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

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

@kaplan81

Description

@kaplan81

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions