问题
Below route defines to store json data as MyCachedData in cache storage, and IndexDb only stores the url and timestamp.
workboxSW.router.registerRoute('/MyApi(.*)',
workboxSW.strategies.staleWhileRevalidate({
cacheName: 'MyCachedData',
cacheExpiration: {
maxEntries: 50
},
cacheableResponse: {statuses: [0, 200]}
})
);
Is it possible to store the json data in the index db only and how can you define it to intercept (add, update, delete) using Workbox?
回答1:
No, Workbox relies on the Cache Storage API to store the bodies of responses. (As you've observed, it uses IndexedDB for some out-of-band housekeeping info, like timestamps, used for cache expiration.)
If an approach that uses the Cache Storage API isn't appropriate for your use case (it would be good to hear why not?), then I'd recommend just updating IndexedDB directly, perhaps via a wrapper library like idb-keyval.
回答2:
You can write a custom function that performs a fetch and stores the information in indexedDB, but this would be seperate from anything Workbox does outside of making sure you only get the API requests.
This is not tested, but something like:
workboxSW.router.registerRoute(
'/MyApi(.*)',
(event) => {
// TODO:
// 1. Check if entry if in indexedDB
// 1a. If it is then return new Response('<JSON Data from IndexedDB>');
// 1b. If not call fetch(event.request)
// Then parse fetch response, save to indexeddb
// Then return the response.
}
);
来源:https://stackoverflow.com/questions/45696113/workbox-is-caching-only-time-stamps-to-indexdb-how-to-intercept-with-json-data