I am using service-worker to cache a few static files but I am also trying to cache my json data in the indexedDB. So that whenever my app accesses the url "www.someurl.com/api/my-items" it gets intercepted by the service worker and instead, a custom response is returned with my indexedDB data.
I am using the promise based idb from here https://github.com/jakearchibald/idb
So far I came up with the following code. As I understand, I need to intercept the fetch event and return a custom response.
importScripts('idb.js');
var pageCache = 'v1';
var idbName = 'data';
var idbTableName = 'idbtable';
var cacheFiles = [
'../js/',
'../css/file1.css',
'../css/fle2.css'
];
//Install and Activate events
//...
//Fetch Event
self.addEventListener('fetch', (event) => {
var requestUrl = new URL(event.request.url);
if (requestUrl.origin !== location.origin) {
//...
if(event.request.url.endsWith('/api/my-items')){
event.respondWith(
idb.open(idbName, 1).then((db) => {
var tx = db.transaction([idbTableName], 'readonly');
var store = tx.objectStore(idbTableName);
return store.getAll();
}).then(function(items) {
return new Response(JSON.stringify(items), { "status" : 200 , "statusText" : "MyCustomResponse!" })
})
)
}
//...
}
})
I am trying to understand if there is a cleaner way of writing this code, without specifically creating a response with "new Response()". I am sure there is a promise based concept I do not fully understand.