首页 文章

拦截fetch事件并返回indexedDB数据

提问于
浏览
1

我正在使用service-worker来缓存一些静态文件,但我也试图将我的json数据缓存在indexedDB中 . 因此,每当我的应用访问网址“www.someurl.com/api/my-items”时,它都会被服务工作者截获,而是使用我的indexedDB数据返回自定义响应 .

我在这里使用基于承诺的idb https://github.com/jakearchibald/idb

到目前为止,我想出了以下代码 . 据我了解,我需要拦截fetch事件并返回自定义响应 .

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!" })
              })

          )

        } 

        //...
    }
 })

我试图了解是否有更简洁的方法来编写此代码,而无需专门创建带有“new Response()”的响应 . 我确信有一个基于承诺的概念,我不完全理解 .

2 回答

  • 2

    我建议使用像Workbox这样的帮助程序库来实现Cache Storage API . This SO answer讨论了使用IndexDB -idb帮助程序类与缓存API - 工作框 .

    Workbox是Chrome团队的领导PWA实施的团队 . 另外,WorkBox是他们新的重写lib(来自sw-precache),经过多年的学习 . 值得考虑 .

  • 1

    我遇到了相同的情况,其中我不需要自定义响应拦截Http调用,并在索引数据库中查看相同的URL,我已经推送了URL和响应并从那里读取并作为响应

    在Service worker fetch事件中,我实现了 network first approach ,这意味着如果发生任何错误,它将首先查找服务,然后从索引数据库中读取并返回响应 .

    fetch(event.request).catch(function(result){});

    self.addEventListener('fetch', function (event) {
         if (event.request.url.includes('[yourservicecallName]')) {
                    event.respondWith(
                        fetch(event.request).catch(function (result) {
                           return readtheDatafromIndexedDb('firstDB', 'firstStore', event.request.url).then(function(response)
                            {
                                return response;
                            });
                        })
                    );
                }
      });
    

    从索引数据库读取并返回响应的方法

    function readtheDatafromIndexedDb(dbName, storeName, key) {
       return new Promise((resolve, reject) => {
        var openRequest = indexedDB.open(dbName, 2);
        openRequest.onupgradeneeded = function (e) {
            let db = request.result;
            if (!db.objectStore.contains(storeName)) {
                db.createObjectStore(storeName, { autoIncrement: true });
            }
        }
        openRequest.onsuccess = function (e) {
            console.log("Success!");
            db = e.target.result;
            var transaction = db.transaction([storeName], "readwrite");
            var store = transaction.objectStore(storeName);
            var request = store.get(key);
            request.onerror = function () {
                console.log("Error");
                reject("unexpected error happened");
            }
            request.onsuccess = function (e) {
                console.log("return the respose from db");
                //JSON.parse(request.result)
                resolve(new Response( request.result, { headers: { 'content-type':'text/plain' } } ));
            }
        }
        openRequest.onerror = function (e) {
            console.log("Error");
            console.dir(e);
        }
       });
    
    }
    

    希望这会帮助你 .

相关问题