StaleWhileRevalidate:一旦遇到非成功状态,就从缓存中移除

StaleWhileRevalidate: Remove from cache once a non-success status is encountered

我们正在使用 Workbox 的 StaleWhileRevalidate 策略来缓存 JSON API 的响应。在正常情况下,这个 API 将以状态码 200 响应并传递所需的数据。

但是,用户可能不再有权访问该数据。在那种情况下,我们的 JSON API 响应状态 401.

不幸的是,我们的应用仍然“看到”缓存的 JSON 响应。

一旦遇到 401,我可以使用 Workbox 中的任何设置或挂钩来删除缓存的条目吗?或者还有其他建议或最佳做法可以遵循吗?

所以,这是我的解决方法:

我使用 workbox.cacheableResponse.Plugin 允许缓存 401 响应。然后,我添加了另一个插件,它检查缓存的响应是否成功。如果没有(即 401 收到),我将 return 没有缓存结果:

workbox.routing.registerRoute(
  /^\/api\/data.json$/,
  new workbox.strategies.StaleWhileRevalidate({
    plugins: [
      // explicitly allow to cache `401` …
      new workbox.cacheableResponse.Plugin({ statuses: [0, 200, 401] }),
      // … but do not return a cached result
      // in this case (!cachedResponse.ok)
      {
        cachedResponseWillBeUsed: ({ cachedResponse }) => {
          return (cachedResponse && cachedResponse.ok) ? cachedResponse : null;
        }
      }
    ]
  })
);

我建议编写一个使用 cacheWillUpdate 回调的自定义插件,并在传入 Response 的状态为 401 时采取适当的措施。 (workbox-cacheable-response 在幕后使用 cacheWillUpdate,但您需要更大的灵活性,因此编写自己的逻辑很有意义。)

类似于:

// Or use workbox.core.cacheNames.runtime for the default cache.
const cacheName = 'my-api-cache';

const myPlugin = {
  cacheWillUpdate: async ({response}) => {
    if (response.status === 401) {
      const cache = await caches.open(cacheName);
      await cache.delete(response.url);
      return null;
    }

    // Add in any other checks here, if needed.
    return response;
  },
};

workbox.routing.registerRoute(
  /^\/api\/data.json$/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName,
    plugins: [myPlugin],
  })
);