João Pires
João Pires

Reputation: 1007

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

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.

Upvotes: 1

Views: 154

Answers (1)

Petr Broz
Petr Broz

Reputation: 9934

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

Upvotes: 2

Related Questions