我如何知道 Service Worker 通过 Workbox 缓存的响应的日期时间?

How can I know the datetime of a response cached by a service worker through Workbox?

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

例如,假设来自 Web API 的响应是这样缓存的:

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

一小时内,响应将来自缓存,如果用户离线,响应时间可能会更长。

我怎么知道原来的回复date/time?

您可能希望从响应的 Date: header 中检索该信息。不幸的是,如果您正在处理来自 third-party 服务器的 CORS 响应,默认情况下 Date: header 不可用——只有 simple response headers 可用。

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

我不知道您是如何阅读网络应用程序中的 API 响应的,但我们假设您正在使用 fetch() 来获取响应(可能会也可能不会来自 service worker 的缓存),然后将响应处理为 JSON。检查 Date: header 的代码可能类似于:

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.
}