StaleWhileRevalidate:一旦遇到不成功状态,则从缓存中删除

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

但是,可能会发生用户不再有权访问该数据的情况。在这种情况下,我们的JSON API会以status响应401

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

一旦我们遇到一个问题,Workbox中是否有任何设置或挂钩可以用来修剪缓存的条目401?还是要遵循其他建议或最佳做法?


泛舟湖上清波郎朗
浏览 325回答 2
2回答

临摹微笑

我建议你写一个使用的自定义插件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],  }));

翻翻过去那场雪

因此,这是我的解决方法:我使用workbox.cacheableResponse.Plugin来缓存401响应。然后,我添加了另一个插件,该插件检查缓存的响应是否成功。如果没有(即401收到),我将不返回任何缓存结果: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;        }      }    ]  }));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript