2

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?

seUser
  • 1,093
  • 2
  • 10
  • 21

2 Answers2

2

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.

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
  • If you use IndexDb for background sync and update the json record in indexDb using offline mode then shouldn't it be able to fetch the latest from the indexDb in the offline mode? – seUser Aug 15 '17 at 19:16
  • IndexedDB is used within `workbox-background-sync` to store the serialized **request** bodies, not **response** bodies. I assume you're talking about storing response bodies, and either using the Cache Storage API (which should be the easiest approach) or rolling your own IndexedDB code would be necessary. Workbox doesn't provide a helper for doing that. – Jeff Posnick Aug 15 '17 at 19:48
  • Thanks! Is there a reason response bodies are not supported, and is it a good practice if I end up doing that using my own IndexDb code? – seUser Aug 15 '17 at 19:54
  • The `workbox-background-sync` library makes it easy to retry requests that resulted in a failure. Since it only write something to IndexedDB when there's a failure to get a response, there's no response body that could be written. If you're just interested in caching and reusing valid responses, using the built-in support in Workbox for the Cache Storage API (via one of the workbox.strategies.*) will do that for you. – Jeff Posnick Aug 15 '17 at 20:02
1

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.
  }
);
Matt Gaunt
  • 9,434
  • 3
  • 36
  • 57