1

I have a SPA application and trying to implement support for PWA using a service worker. I cache an offline.html file which I want to display on any network errors. I can't get it to work as I want when my REST API calls fails due to no internet.

Whenever a API call fails, I want to return a custom Response object with e.g. status code 599, a short status text and the full content of the cached offline.html file.

var CACHE_NAME = 'hypo-cache-v1';
var urlsToCache = [
    'home/offline.html',
    'manifest.json',
    'favicon.ico'
];

self.addEventListener('install', function(event) {
    self.skipWaiting();

    // Perform install steps
    event.waitUntil(
        caches.open(CACHE_NAME).then(function(cache) {
            console.log('Opened cache');
            try {
              return cache.addAll(urlsToCache);
            } catch (error) {
                console.error(error);
            }
        })
    );
});

self.addEventListener('fetch', function(event) {
    // if (event.request.mode !== 'navigate' && event.request.mode !== 'cors') {
    // if (event.request.mode !== 'navigate') {
    if (event.request.mode === 'no-cors') {
        // Not a page navigation, bail.
        return;
    }

    console.log('[ServiceWorker] Fetch', event.request.url, event.request.mode);

    event.respondWith(
        fetch(event.request)
            .then(function(response) {
                return response;
            })
            .catch(function(error) {
                console.error("poa: catch", event.request.url, error, event);

                if (event.request.url.indexOf("/api/") !== -1) {

                    var customResponse = null;

                    caches.match('home/offline.html').then(function(response) {
                        if (response) {
                            response.text().then(function(responseContent) {

                                var fallbackResponse = {
                                    error: {
                                        message: NETWORK_ERROR_TEXT,
                                        networkError: true,
                                        errorPage: responseContent
                                    }
                                };
                                var blob = new Blob([JSON.stringify(fallbackResponse)], {type : 'application/json'});
                                customResponse = new Response(blob, {"status" : 599, "statusText": NETWORK_ERROR_TEXT, "headers" : {"Content-Type" : "application/json"}});
                                // var customResponse = new Response(NETWORK_ERROR_TEXT, {"status" : 599, "statusText": NETWORK_ERROR_TEXT, "headers" : {"Content-Type" : "text/plain"}});
                                console.log("poa: returning custom response", event.request.url, customResponse, fallbackResponse);
                                return customResponse;
                            });
                        }
                    });

                    console.log("poa: how to avoid getting here???", event.request.url, customResponse);

                    // var fallbackResponse = {
                    //     error: {
                    //         message: NETWORK_ERROR_TEXT,
                    //         networkError: true
                    //     }
                    // };
                    // var blob = new Blob([JSON.stringify(fallbackResponse)], {type : 'application/json'});
                    // var customResponse = new Response(blob, {"status" : 599, "statusText": NETWORK_ERROR_TEXT, "headers" : {"Content-Type" : "application/json"}});
                    // console.log("poa: returning custom response", event.request.url, customResponse);
                    // return customResponse;
                } else {
                    return caches.match('home/offline.html');                    
                }
            })
    );
});

I must be missing something basic with the promises but can't figure it out. I want to return the customResponse in the caches.match() promise, but instead the customResponse is returned but only after the console.log("poa: how to avoid getting here???");, which makes the initiating ajax call receive a response with status 0 and statusText "error". I want to get my custom response...

Here is the code for calling code:

                $.ajax({
                    url: url,
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    cache: false,
                    headers: {
                        "Authorization": "Bearer " + token
                    },
                    'timeout': timeout,
                    beforeSend: function(jqXhr, options) {
                        this.url += "-" + userId;
                        logUrl = this.url;
                    }

                }).done(function(data) {

                    done(null, data);

                }).fail(function(data, textStatus, errorThrown) {

                    var end = Date.now();
                    var diff = end - start;
                    console.error("Error fetching from resource: ", diff, timeout, data, textStatus, errorThrown, new Error().stack);
...
...

How should I rewrite my fetch and catch so I can return my customResponse to the caller?

poa
  • 101
  • 2
  • 14
  • 2
    @pawan The question is about how to handle this scenario when i'm offline, so there is no backend to send it to. – poa Aug 06 '19 at 10:24

1 Answers1

1

I found the error myself... I forgot to add a few return in the promise chain.

For anyone who might be interested, here's the working updated code:

    event.respondWith(
        fetch(event.request)
            .then(function(response) {
                return response;
            })
            .catch(function(error) {
                console.error("poa: catch", event.request.url, error, event);

                if (event.request.url.indexOf("/api/") !== -1) {

                    var customResponse = null;

                    return caches.match('home/offline.html').then(function(response) {
                        if (response) {
                            return response.text().then(function(responseContent) {

                                var fallbackResponse = {
                                    error: {
                                        message: NETWORK_ERROR_TEXT,
                                        networkError: true,
                                        errorPage: responseContent
                                    }
                                };
                                var blob = new Blob([JSON.stringify(fallbackResponse)], {type : 'application/json'});
                                customResponse = new Response(blob, {"status" : 599, "statusText": NETWORK_ERROR_TEXT, "headers" : {"Content-Type" : "application/json"}});
                                // var customResponse = new Response(NETWORK_ERROR_TEXT, {"status" : 599, "statusText": NETWORK_ERROR_TEXT, "headers" : {"Content-Type" : "text/plain"}});
                                console.log("poa: returning custom response", event.request.url, customResponse, fallbackResponse);
                                return customResponse;
                            });
                        }
                    });
...
...
...
poa
  • 101
  • 2
  • 14
  • Now that it's working, you can do some tidying ..... `.then(function(response) { return response; })` can be purged. – Roamer-1888 Aug 06 '19 at 13:48
  • `customResponse` doesn't need to be an outer var. You can write `var customResponse = new Response(...)` or purge the `console.log()` and write `return new Response(...)`. – Roamer-1888 Aug 06 '19 at 13:48
  • Without `else {...}` clauses on the two ifs, the function has unhandled cases. – Roamer-1888 Aug 06 '19 at 13:50