Workbox is caching only time stamps to indexDb, how to intercept with json data in indexDb?

天大地大妈咪最大 提交于 2019-12-24 00:33:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!