How to return blob item from localForage in service worker?

414 Views Asked by At

in my service worker i store mp4 video in indexedDB with localforage library in a blob data. It's work ! but i don't know how can i return this blob data.

This is my fetchHandler code :

const fetchHandler = async (event) => {
    const getResponse = async () => {
        const request = event.request;
        if( request.destination === 'video' ){
            // Get from indexedDB
            const value = await localforage.getItem('video');
            // How return the video from indexedDB cache ?
            if( value ) return value; // not working
            // Add in indexedDB
            var networkResponse = await fetch(event.request);
            localforage.setItem('video', networkResponse.blob() ).then(function (value) {
                // Do other things once the value has been saved.
                console.log(value);
            }).catch(function(err) {
                // This code runs if there were any errors
                console.log(err);
            });
        }else{
            const openedCache = await caches.open(SW_CACHE_NAME);
            const cacheResponse = await openedCache.match(request);
            if (cacheResponse) return cacheResponse;

            var networkResponse = await fetch(event.request);
            const cachePutResponse = await openedCache.put(request, networkResponse.clone());
            if (cachePutResponse) return cachePutResponse;
        }

        return networkResponse;
    };
    event.respondWith(getResponse());
};

thanks for your help

1

There are 1 best solutions below

0
Jeff Posnick On

You need to pass a valid Response object to event.respondWith(). That entails a response body (which is what you get back from localforeage.getItem()), but also some response headers.

You can use the Response constructor to create that, and return it from your getResponse() function.

The code could look something like:

const value = await localforage.getItem('video');
if (value) {
  // See https://fetch.spec.whatwg.org/#bodyinit for what's accepted
  // as a BodyInit.
  return new Response(value, {
    headers: {
      // Replace this with the actual MIME type for the video.
      'content-type': 'video/mp4',
      // Include any other headers here if desired.
    }
  });
}