MikMik
MikMik

Reputation: 3466

Put "hand-made" response in cache

I'm trying to add some offline capabilities to my web app. Under certain circumstances, I want to fetch the data from a request/response in the cache, change it, and add it back to the cache as a new request/response pair.

So far, I've been able to get the data from the cache and modify it, but when I put it in the cache, I get an empty cache entry (Content-Length: 0). EDIT: Actually, Chrome Developer Tools show, in the preview pane, the correct object, but in the cache entries list it says "Content-Length: 0" and "Time Cached: 1/1/1970 0:59:59".

And then, when trying to fetch it again from the cache, I get a no-match error, and cache.match() returns undefined.

This is what I have so far:

return caches.open(CACHE_NAME).then(function(cache) {
    return cache.matchAll().then(function(responses) {
        var resp = responses[0].clone();
        return resp.clone().json().then(function (datosResp) {

            var nuevaMed = nuevaMedicionDesdeMedicion(datosResp);
            var urlACachear = new URL('obra/' + nuevaMed.obraId + '/mediciones/' + nuevaMed.id, urlBase);

            var nuevaMedJSON = JSON.stringify(nuevaMed);
            var blob1 = new Blob([nuevaMedJSON], { type: "application/json;charset=utf-8" });
            var myHeaders = new Headers(resp.headers);

            var resACachear = new Response(blob1, { "status": 200, myHeaders });

            return cache.put(urlACachear, resACachear.clone()).then(function() {
                // Whatever...
            });
        });
    });
});

Any ideas on how to do this? Is it even possible to store and correctly retrieve my own requests and responses?

Upvotes: 1

Views: 593

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

The Time Cached: 1/1/1970 0:59:59 is a known bug in Chrome's DevTools. I'd imagine that the Content-Length: 0 is the same bug.

What you describe sounds like your new Response is being properly written to the cache, but there's something wrong with the your call to match() that is preventing you from finding the cached entry.

As a quick sanity check, you can run the following code in the JS console to get a list of all the URLs used as keys in your CACHE_NAME cache. Make sure that you see the URLs you expect to be cached printed out, and then explicitly try performing a match() using one of those URLs.

const cache = await caches.open(CACHE_NAME);
const requests = await cache.keys();
const urls = requests.map(request => request.url);
console.log(urls):

Upvotes: 1

Related Questions