我怎么知道服务工作者通过Workbox缓存的响应的日期时间?

时间:2019-02-20 15:19:52

标签: caching service-worker progressive-web-apps workbox

在我的应用程序中,重要的是,用户必须知道上次更新数据的时间。

例如,假设来自Web API的响应被缓存如下:

workbox.routing.registerRoute(
  /https:\/\/api\.service\.com\/resource.*/,
  workbox.strategies.cacheFirst({
    cacheName: 'resource',
    plugins: [
      new workbox.expiration.Plugin({
        maxAgeSeconds: ONE_HOUR,
      }),
    ]
  }),
)

在一个小时内,响应将来自缓存,如果用户处于脱机状态,响应时间可能会更长。

我怎么知道原始回复日期/时间?

1 个答案:

答案 0 :(得分:1)

您可能希望从响应的Date:标头中检索该信息。不幸的是,如果您要处理来自第三方服务器的CORS响应,则默认情况下Date:标头不可用-仅simple response headers可用。

因此,您要做的第一件事就是确保您使用的API在其HTTP响应上设置了Access-Control-Expose-Headers: Date

我不知道您如何在Web应用程序中读取API响应,但是假设您正在使用fetch()来获取响应(可能来自或可能不来自服务工作者的缓存) ),然后将响应作为JSON处理。检查Date:标头的代码可能类似于:

const response = await fetch('https://api.service.com/resource');
const dateAsString = response.headers.get('Date');
const dateAsMillis = Date.parse(dateAsString);

// Do something with dateAsMillis, like comparing it to Date.now().
if ((Date.now() - dateAsMillis) < SOME_THRESHOLD) {
  const json = await response.json();
  // Etc.
}