Retrieve 'Time-Cached' from response returned via CacheStorage api via cache.match(req)
Asked Answered
D

2

7

I am using the new CacheStorage api and want to have a little job that cleans up old cached entries that are above a certain ttl (time to live).

In Chrome Dev Tools -> Application tab I see a 'Cached-Time' column but there is no way to retrieve this via the api.

const cache = await caches.open(`my-cache`);
const response = await cache.match(new Request(`https://someurl`))
console(response.cachedTime) <- // doesn't exist

I tried getting it via the Date header, but that only works for non-cors requests. The devtools somehow keeps track of all requests. Is there a way to get this information dyanamically via the CacheStorage api ?

// this is not a bullet proof method
// doesn't work for cors or if response doesn't send a Date header
console.log(response.headers.get(`date`));

Tried dumping the entire response and inspecting it but I didn't see anything useful.

Discontinuation answered 30/8, 2019 at 17:6 Comment(0)
L
0

I did an extensive research but I didn't find anything conclusive.

I ended-up checking the Date response header (which is returned by most API) to know how old the resource were.

In case the Date response header were missing, I simply don't cache the response and print a warning in the console.

Note that an API can return an inaccessible Date header due to the CORS configuration (check the Access-Control-Expose-Headersresponse header to know more)

Laomedon answered 1/12, 2022 at 13:22 Comment(0)
D
0

When storing the response in the cache, you can add a custom header to it which would store the time at which it was cached.

Here's how you can do it -

const response = await axios.get(URL, config);

// Construct new headers based on the response's header to add 'cached-time'
const newHeaders = new Headers(response.headers);
newHeaders.set("cached-time", Date.now());

const data = new Response(JSON.stringify(response.data), {
  headers: newHeaders,
});

// Putting fetched or combined data into cache
cacheStorage.put(URL, data);

Then you can retrieve the time for which the response has been cached as follows -

const cachedTime = cachedResponse.headers.get("cached_time");

const timeElapsed = (Date.now() - cachedTime) / 1000;
Draper answered 30/3, 2023 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.