无法在IndexedDB中存储项

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

我对Javascript和PWA是相当陌生的。我遵循了一个教程,使用了那里使用的相同代码,但我没有设法在IndexedDB中存储数据。我使用Jake Archibald的idb-Wrapper
这是我的服务人员:

importScripts('/src/js/idb.js');

// here: code for installing and activating the sw

const db = idb.openDB('incidents-store', 1, {
    upgrade(db) {
        const store = db.createObjectStore('incidents', {
            keyPath: 'id',
            autoIncrement: true,
        });
        store.createIndex('id', 'id');
    },
}); 

self.addEventListener('fetch', event => {
    if (!(event.request.url.indexOf('http') === 0)) return;
    const url = 'http://localhost:3000/incidents';
    if(event.request.url.indexOf(url) >= 0) {
        event.respondWith(
            fetch(event.request)
                .then ( res => {
                    const clonedResponse = res.clone();
                    clonedResponse.json()
                        .then( data => {
                            for(let key in data)
                            {
                                db
                                    .then( dbIncidents => {
                                        let tx = dbIncidents.transaction(['incidents'], 'readwrite');
                                        let store = tx.objectStore('incidents');
                                        store.put(data[key]);
                                        return tx.done;
                                    })
                            }
                        })
                    return res;
                })
        )
    } else {// other code not important for my ask for help}
})

所发生的情况是,代码确实打开了IndexedDB,但并不存储我试图用“store.put(data[key])”放入其中的项;“。虽然数据的格式似乎正确,但当我将其打印到控制台时:数据[关键字] = {id:6、日期:“2021年1月25日23时00分00秒”、时间:“09:30:41”,姓名:“Meltem”}。(这是对具有自动递增ID的数据库的请求)。
你知道问题出在哪里吗?

8qgya5xd

8qgya5xd1#

我建议仔细查看idb库的文档:https://github.com/jakearchibald/idb
几乎所有的方法都是异步的,并且返回一个promise。这个documentation on promises应该会有帮助,就像this guidance在使用promise时使用async/await作为.then()链的替代品一样。
您必须自定义您的代码以实际实现您想要的功能,但它基本上采用以下结构:

importScripts('https://unpkg.com/idb/build/iife/index-min.js');

async function addToIDB(data) {
  // Assume that db is an already open IDB instance.
  // Tweak the transcation logic and other IDB operations as needed.
  for (const value of Object.values(data)) {
    const tx = db.transaction(['incidents'], 'readwrite');
    const store = tx.objectStore('incidents');
    await store.put(value);
    await tx.done;
  }
}

async function incidentResponse(request) {
  const response = await fetch(request);

  const clonedResponse = response.clone();
  const data = await clonedResponse.json();
  await addToIDB(data);

  return response;
}

self.addEventListener('fetch', (event) => {
  const url = 'http://localhost:3000/incidents';
  if (event.request.url.startsWith(url)) {
    event.respondWith(
      incidentResponse(event.request)
    );
  }
});

相关问题