4

I thought it would be rather simple but I am struggle to successfully send response then modify my cloned response that is being stored in cache inside my service worker.

Ultimately I want to appended my cached data with the time and date of the fetch. I am using my service worker to first fetch this data from the network and if its not available fallback to the cache.

This is the code from my service worker

        event.respondWith(
            fetch(event.request)
            .then(function(e) {

                console.log('response', e)
                var responseToCache = e.clone();

                responseToCache.json().then(function(data) {
                    var today = new Date();
                    var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
                    var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
                    data.cached = { date: date, time: time }
                    return data
                })

                // var init = {
                //     status: response.status,
                //     statusText: response.statusText,
                //     headers: { 'X-Foo': 'My Custom Header' }
                // };

                // response.headers.forEach(function(v, k) {
                //     init.headers[k] = v;
                // });

                // var responseToCache = response.text().then(function(body) {
                //     var today = new Date();
                //     var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
                //     var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
                //     var bodyObj = JSON.parse(body)

                //     bodyObj.cached = { date: date, time: time }
                //     body = JSON.stringify(bodyObj)

                //     return new Response(body, init);
                // });

                caches.open(CACHE_NAME)
                    .then(function(cache) {
                        cache.put(requestURL, responseToCache);
                    });

                return e
            })
            .catch(function() {
                console.log('data offline')
                return caches.match(requestURL);
            })
        );
maulpets
  • 51
  • 3

0 Answers0