Re: [w3c/ServiceWorker] Replaying POST requests (#693)

@jakearchibald one problem with using IDB is that it's much more complicated than the simplicity of CacheStorage.  Also, having to deconstruct request objects and reconstruct them later is very fiddly and error-prone.  
(For example, someone could easily mix up the body and url when reconstructing the request object).

A simpler (yet very hacky) approach I found was to store all my POST requests in a separate cache storage instance and just change the method on the way in and out.
So adding a POST request looks like:
```js
 const cache = await caches.open(ACTION_CACHE);
 cache.put(new Request(request, {method: "GET"}), new Response());
```
and retrieving them all for processing later looks like:
```js
 const cache = await caches.open(ACTION_CACHE);
 const actionQueue = await cache.keys();
 // cache.keys doesn't return requests in date order, so need to sort them
 actionQueue.sort((a,b) => {
  return  getRequestTime(a) - getRequestTime(b);
 });
 return actionQueue.map(request => new Request(request, {method: "POST"}));
```
I've not tested this extensively, but it works for my particular use case (my requests are all very simple and don't have custom bodies or headers).  Hope someone finds that useful.

I know this is abusing CacheStorage for something it's not made for.  But CacheStorage is the closest thing I've found to a persistent FIFO queue of native Request objects.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/693#issuecomment-803681723

Received on Sunday, 21 March 2021 23:41:28 UTC