IndexedDB 如何在service worker中从localForage返回blob项?

rdrgkggo  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(1)|浏览(123)

在我的服务工作者我存储mp4视频在indexedDB与本地搜索库在一个blob数据。它的工作!但我不知道如何才能返回这个blob数据。
下面是我的fetchHandler代码:

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());
};

谢谢你的帮助

vhmi4jdf

vhmi4jdf1#

您需要将一个有效的Response对象传递给event.respondWith(),这需要一个响应主体(即从localforeage.getItem()返回的内容),以及一些响应头。
您可以使用Response构造函数来创建它,并从getResponse()函数返回它。
代码可能类似于:

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.
    }
  });
}

相关问题