How can I find which cache a service worker response belongs to?

109 views Asked by At

Given a request, how can I figure it out which cache it belongs to? match, despite searching in all caches, will only give me the cached response. I would like to retrieve both the cache object / cache's name and the cached response.

1

There are 1 answers

0
Petr Broz On

If you need to know the cache the response is in, I'm afraid you'll need to call match on each of the caches individually until you find one where there's a match.

The code could look something like this:

async function findCachedResponse(request) {
    const cacheKeys = await caches.keys();
    const openCaches = await Promise.all(cacheKeys.map(cacheKey => caches.open(cacheKey)));
    const matches = await Promise.all(openCaches.map(cache => cache.match(request));
    const i = matches.findIndex(match => match !== undefined);
    if (i !== -1) {
        return { cache: cacheKeys[i], response: matches[i] };
    } else {
        return undefined;
    }
}