How to Cache Additional Items in a Workbox Plugin

336 Views Asked by At

I'd like to write a Workbox plugin that intercepts a particular API call, does some logic (omitted from the code below) that determines other URL's that can be cached, then adds them to the runtime cache.

export class PreCachePlugin implements WorkboxPlugin {
  fetchDidSucceed: WorkboxPlugin["fetchDidSucceed"] = async ({
    response,
  }) => {
    if (response.ok) {
      const clonedResponse = await response.clone();
      const json = await clonedResponse.json();
      const urls: string[] = getUrlsToCache(json); // Omitting this logic.
      await Promise.all(urls.map(url => {
        const response = await fetch(url);
        // TODO: How do I fetch these URL's and put them in the cache configured
        // below while still respecting the expiration.maxEntries setting below?
      }));
    }
  }
}

I am using GenerateSW with workbox-webpack-plugin and adding my plugin:

new GenerateSW({
  include: [/\.js$/, /\.json$/, /\.html$/],
  runtimeCaching: [
    {
      urlPattern: ({ url }) => url.toString().endsWith("/foo"),
      handler: "StaleWhileRevalidate",
      options: {
        cacheName: "Foo",
        expiration: { maxEntries: 100 },
        plugins: [
          new PreCachePlugin(),
        ],
      },
    },
  ],
  swDest: "./sw.js",
}

How do I fetch the above new URL's and put them in the configured runtime cache while still respecting the expiration.maxEntries settings?

0

There are 0 best solutions below