Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting entry in service worker cache based on age

With service workers comes great flexibility and power, but also much responsibility... in terms of keeping the cache under control and not allowing it to grow unnecessarily.

Is there a way to determine the age of a cached item, i.e. the time it has been sitting in the cache, and purge cached items periodically based on age?

I'm thinking here about something along the following lines:

const RUNTIME = 'runtime-cache';

var getAgeOf = function (request) {
    return (*time since request was cached*);  // <-- but HOW?
};

var purgeRuntimeCache = function (threshold) {      
    caches.open(RUNTIME).then(function (cache) {
        cache.keys().then(function (keys) {
            keys.forEach(function (request, index, array) {
                cache.match(request).then(function (response) {
                    if (getAgeOf(request) > threshold) {
                        console.log('delete old resource from runtime cache: ' + request.url);
                        cache.delete(request);
                    }
                });
            });
        });
    });
};
like image 917
drmrbrewer Avatar asked Sep 17 '25 22:09

drmrbrewer


1 Answers

The Workbox folks seems to be parsing the 'date' from the response's headers. They also assume the response to be fresh if the date is not available. Check their source for the cacheExpiration plugin over here. I guess one could also save the caching time to IndexedDB or Caches upon fetching the asset from the network for the first time (the asset url as a key for example).

While it's a good exercise to implement something like this by hand and dig into details, my gut says people should generally be better of by using a library to handle the SW. Workbox might be the best option.

Update:

I haven't tried this out myself but I don't see any reason this wouldn't work in practice.

  • Use something like idb-keyval to make it super simple to use the IndexedDB as a keyval store
  • Use importScript(point this to idb-keyval.min.js) to have it in the SW
  • When you cache something, use its URL (string) as the IDB key and Unix time as as a value
  • Later on, iterate through the cache items and compare them to the timestamps found in IDB; if too old, delte from the cache
like image 139
pate Avatar answered Sep 20 '25 14:09

pate