Storing REST requests with service workers to sync

2020-05-24 01:07发布

问题:

I'm thinking about taking my application to offline using service workers. I'm already achieving satisfying results with caching resources, but I also have to check onfetch whether I'm connected to the internet, if not - store the request, and push it onsync.

I understand, that future onsync will help with that, but I need - even temporary - solution for that.

I've tried just to store the requests in an array within worker, but it's not persistent - doesn't work after computer restart (while SW works and serves offline content).

What's the good direction - storing it in cache like files somehow? Or using IndexedDB / SimpleDB (Accessing indexedDB in ServiceWorker. Race condition)?

回答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 POSTs, 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 HTTP POSTs 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 POSTs might require a valid Authorization 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 HTTP POST's body without much work. If you can't use IndexedDB (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 failed Requests as the keys and empty Response objects as the values. At service worker startup, you could use the keys() method on your "queue" cache to get a list of all the Requests, and for each queuedRequest, call fetch(queuedRequest) to replay it. I have not tried this approach before, but I think it should work.