I'm working on an authoring / CMS type application. The application allows concurrent editing of various 'blocks' of data. It has supported offline using appache and indexDB. With this approach I know if my data is coming from the network or from the cache. Now I'd like to migrate things to use service workers and the new cache api.
I need a way to know if my data (request) was served from the cache or the network so I can inform the users they are possibly looking at stale data so any any edits may override data they don't know about. IMO, this would a pretty common thing to do but it's turning out not to be so easy...
I'm currently trying to get things working using WorkBox but I'd be more than happy with a native solution. Using Workbox I've tried to set a new header on the response but Chrome complains about
const apiStrategy = workbox.strategies.cacheFirst({
cacheName: 'data-cache',
cacheExpiration: {
maxEntries: 100,
maxAgeSeconds: 3600 * 24
},
cacheableResponse: { statuses: [200] }
});
workbox.routing.registerRoute(
new RegExp('/api/'),
async ({event, url}) => {
const cachedResponse = await apiStrategy.handle({event, url});
if (cachedResponse) {
const responseClone = cachedResponse.clone();
responseClone.headers.set('x-sw-cache', 'yes');
return responseClone;
}
return cachedResponse;
}
);
So is there any way to know if the response came from the network or the cache?