Re: [slightlyoff/ServiceWorker] Handling race conditions - API for accessing pending requests? (#959)

Some other brainstorming on `self.requests` API (_possible bugs in code_):

```js
self.addEventListener('fetch', event => {
  const request = event.request;
  const url = new URL(request.url);

  if (url.pathname === '/') {
    const result = self.caches.match(request).then(res => {
      if (!res) {
        return loadIndex(request);
      }

      return res;
    });

    event.respondWith(result);
    return;
  }

  const result = self.requests.match(request).then(inflight => {
    return inflight || self.caches.match(request);
  }).then(res => {
    if (res) return res;

    return fetch(request).then(res => {
      if (res && res.ok) {
        putCache(request, res);
      }

      return res;
    });
  });

  event.respondWith(result);
});

function loadIndex(request) {
  // Preload
  [
    '/main.js',
    '/main.css',
    '/logo.png'
  ].forEach(asset => {
    const req = new Request(asset);
    const fetching = fetch(req).then(res => {
      if (res && res.ok) {
        return putCache.then(() => res);
      }

      return res;
    });

    // Puts request / request + response into memory store
    // until `fetching` is settled
    self.requests.putUntil(req, fetching);
  });

  return fetch(request).then(res => {
    if (res && res.ok) {
      putCache(request, res);
    }

    return res;
  });
}

function putCache(req, res) {
  return caches.open('cache').then(cache => {
    return cache.put(req, res);
  });
}
```

Here main page's assets are requested along side with it and are picked inside `fetch` event via `self.requests` API if requests are _inflight_ or via `self.caches` if they are already cached.  
`self.request.putUntil()` puts a requests to the store until request finishes. There possible could be other methods or options to put request forever (until all clients of the scope are closed) for given time.  
For the case with _pre-flight_ `navigate` request and _PlzNavigate_, the request could be passed there until `fetch` event for the navigate is responded. 

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

Received on Friday, 19 August 2016 20:06:08 UTC