[ServiceWorker] Allow custom cache keys for request caching (#805)

At the moment, `Cache.match()` and `Cache.matchAll()` use a `RequestInfo` object as the cache key (i.e., either a `Request` or a string that turns into a `Request`). This is nice and simple for the common case, but it'd be nice to provide a way for developers to explicitly specify the cache key as a string.

Use cases:

* In case of one-time/expiring URLs, the cache key should be the subset of the URL that doesn't expire (stripping out the authentication stuff).
* In case of offline mode, if you haven't cached user avatars but you *have* cached a generic avatar, you could rewrite a request to the user avatar to fall back to the generic avatar.
* In case of multiple requests actually resolving to the same content (despite having different URLs), a developer could save cache space by reusing the same single cache for multiple requests. You might say "Why use different URLs if the content is the same?" but this might be some legacy system out of the developer's control.

(I am aware of `ignoreSearch`, `ignoreVary` and `ignoreMethod` but they might not cover all potential cases.)

I wrote about the expiring-URL use case in detail [on my blog](http://www.holovaty.com/writing/service-worker-cache-names/), and in my own projects I'm solving it with a hack that I discovered in a [comment](https://github.com/slightlyoff/ServiceWorker/issues/657#issuecomment-151866195) that @jeffposnick made in this project's issue tracker. You can hack around the lack of customizable cache keys by simply using a separate `Cache` for each object you're caching (because you can indeed control the name of `Cache` objects). I made a working demo of this [here](https://gist.github.com/adrianholovaty/0568c895fafd9417e13c#file-serviceworker-cache-wrapper-js).

Another (possibly lousy) reason to add this is: it's already possible with the aforementioned hack, so we might as well make a cleaner way to do it.

If we agree to make this addition to the API, it might make more sense to create new `Cache` methods rather than overloading `match()` and `matchAll()` -- because these existing methods already accept strings as their first argument. I think `get(cacheKeyString)` is a decent contender, though I could see people confusing `match()` and `get()` regularly.

---
Reply to this email directly or view it on GitHub:
https://github.com/slightlyoff/ServiceWorker/issues/805

Received on Sunday, 27 December 2015 20:09:38 UTC