Vetrivel
Vetrivel

Reputation: 306

How to conditionally cache bust an API in workbox

Details about my goal.

I have workbox webpack plugin configured to cache an API for a duration of 30 seconds. I would like to force cache bust it conditionally when a different API request is triggered.

Example, below config caches feature-flags. I am trying to cache bust it when the page sends a request to "updateTests".

workbox configuration to cache feature-flag workbox configuration to cache feature-flag Workbox configuration updated to clear feature-flags Workbox configuration updated to clear feature-flags Cache clear makes it work enter image description here

Things I have tried

Upvotes: 1

Views: 843

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

Just to make sure I understand:

  • You have API calls that include the feature-flags in their URL, and you want all of those calls to be served cache-first out of the cache named api, with a 30 seconds max lifetime.

  • If at any point the browser makes a request for a URL that contains updateFlags, that should serve as kind of a "kill switch" that automatically clears out the contents of the api cache, ensuring that the next feature-flags request will always go against the network.

Assuming that's an accurate summary, you could add a new runtimeCaching route to your configuration that does the following:

runtimeCaching: [{
  // existing route
}, {
  urlPattern: new RegExp('updateFlags'),
  handler: async ({request, event}) => {
    // Deleting the 'api' cache will ensure that the next API
    // request goes against the network.
    event.waitUntil(caches.delete('api'));

    // Assuming that you want the actual request for the URL
    // containing updateFlags to be made against the server:
    return fetch(request);
  },
}]

Upvotes: 2

Related Questions