我们使用Workbox的StaleWhileRevalidate
策略来缓存JSON API的响应。在正常情况下,此API将以状态代码200响应并提供所需数据。
但是,用户可能无法再访问该数据。在这种情况下,我们的JSON API以状态401
响应。
不幸的是,我们的应用仍然“看到”缓存的JSON响应。
一旦遇到401
,Workbox中是否有任何设置或挂钩可以用来修剪缓存的条目?或者还有其他建议或最佳实践吗?
我建议编写一个使用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;
}
}
]
})
);