Strategies to cue client requests when offline

Viewed 348

Context

A mobile client web application (html/js) that makes PUT http requests to a tracking endpoint. The application is built on top of cordova, using vuejs vuex, superagent and localforage

Problem

When the client is offline the requests end up with a timeout and the information to transport is lost.

I think the next step is to cue the requests, my question is where does this logic belongs.

Explaining this same problem I've been told that this should be implemented on service workers, but reading about it I don't see any benefit from using that, since the client app does not rely on the response using things like a cached response won't solve my problem.

On the other end I think this could be achieved by storing on the device the cue of requests and delete once its sent successfully to the server.

Question

  1. Is there any recommendation, or good practice to follow regarding this problem?
  2. Should this be implemented on service workers or in the application itself?
  3. Are there any libraries that tackle this same problem?
1 Answers

Your approach should be to store the data in local memory ie cache or IDB then register a sync event in serviceWorker. So that, when your app is online again that sync event will take care of that task.

Here's an example:

Inside the application from where you want to store:

  if ('serviceWorker' in navigator && 'SyncManager' in window) {
    navigator.serviceWorker.ready
      .then(function(sw) {
        var post = {
          data: 'Some Data'
        };
        writeData('sync-posts', post)     //save in local storage
          .then(function() {
            return sw.sync.register('sync-new-posts');
          })
          .then(function() {
            // display that post was saved for background sync (purely optional)
          })
          .catch(function(err) {
            console.log(err);
          });
      });
  } else {
    sendData();     //in-case browser is incompatible
  }                

Inside the serviceWorker do something like this:

self.addEventListener('sync', function(event) {
  console.log('[Service Worker] Background syncing', event);
  if (event.tag === 'sync-new-posts') {
    console.log('[Service Worker] Syncing new Posts');
    event.waitUntil(
      readAllData('sync-posts')     //reading from local storage
        .then(function(data) {
          // upload the data & free up the storage
        })
    );
  }
});          

Tool for managing ServiceWorker: WorkBox

Related