Created
May 7, 2020 02:28
-
-
Save jeffposnick/0b20fb51b4d131afabf2bec59c5da88f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {RouteHandlerCallbackOptions} from 'workbox-core/types'; | |
import {CacheFirst, NetworkFirst} from 'workbox-strategies'; | |
import {registerRoute} from 'workbox-routing'; | |
// Borrowed from https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook#cache-and-network-race | |
function promiseAny(promises: Array<Promise<Response>>): Promise<Response> { | |
return new Promise((resolve, reject) => { | |
promises = promises.map(p => Promise.resolve(p)); | |
promises.forEach(p => p.then(resolve)); | |
promises.reduce((a, b) => a.catch(() => b)) | |
.catch(() => reject(Error('Unable get a response from network or cache.'))); | |
}); | |
}; | |
const cacheName = 'my-cache'; | |
const networkFirst = new NetworkFirst({cacheName}); | |
const cacheOnly = new CacheOnly({cacheName}); | |
const cacheNetworkRaceHandler = async (options: RouteHandlerCallbackOptions) => { | |
return promiseAny([ | |
networkFirst.handle(options), | |
cacheOnly.handle(options), | |
]); | |
}; | |
registerRoute( | |
// Use whatever matchCallback criteria you want. | |
({url}) => url.pathname.includes('/foo/bar'), | |
cacheNetworkRaceHandler | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment