Kev
Kev

Reputation: 5442

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

In my application, it is important for the user to know when the data was updated for the last time.

For example, let's say that the response from a Web API is cached like this:

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

During one hour, the response will come from cache, and it can be much longer if the user is offline.

How can I know the original response date/time?

Upvotes: 0

Views: 862

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

You'd probably want to retrieve that information from the Date: header of the response. Unfortunately, if you're dealing with a CORS response from a third-party server, the Date: header is not available by default—only the simple response headers are available.

So the first thing you'd want to do is make sure that the API you're using sets Access-Control-Expose-Headers: Date on its HTTP responses.

I don't know how you're reading the API response in your web app, but let's assume that you're using fetch() to obtain the response (which may or may not come from the service worker's cache) and then processing the response as JSON. Code to examine the Date: header could look something like:

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

Upvotes: 3

Related Questions