Storing Rest Requests With Service Workers To Sync Them
Solution 1:
There's an example at https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker/offline-analytics of using a service worker to detect failures for certain types of requests (in this case, Google Analytics pings via HTTP GET
), and queue up the failures using IndexedDB
. The queue is examined each time the service worker starts up and if the request can be successfully "replayed" (because the network is now available), it's removed from the queue. While there are no guarantees about when a service worker will start up (background sync events will help with that in the future), you can safely assume that if the someone is actively using your web app, the service worker will revive itself.
This can be generalized to other types of requests, like HTTP POST
s, but there are a few things to think about:
- Make sure your users are aware that their HTTP
POST
is being queued and will be replayed. Since HTTPPOST
s normally modify server-side state, you don't want to surprise users when something changes as a result of a replayed request that's X hours old. - Depending on what service you're calling, HTTP
POST
s might require a validAuthorization
header. If you're using OAuth 2 for authorization, it may use access tokens which have a limited lifespan. A previously valid Authorization token might be expired by the time you replay the request. IndexedDB
is a good choice for queueing your requests, since it offers flexibility in storing arbitrary data, and it should be possible to, e.g., store the HTTPPOST
's body without much work. If you can't useIndexedDB
(you say it's not supported using Cordova), then the only other option I could think of would be to try to make use of the Cache Storage API to create a new "queue" cache, with failedRequest
s as the keys and emptyResponse
objects as the values. At service worker startup, you could use thekeys()
method on your "queue" cache to get a list of all theRequests
, and for eachqueuedRequest
, callfetch(queuedRequest)
to replay it. I have not tried this approach before, but I think it should work.
Post a Comment for "Storing Rest Requests With Service Workers To Sync Them"