简体   繁体   English

IndexedDB - 如何在 object 存储中读取最大 ID

[英]IndexedDB - How to read max id in object store

I'm working on an a web app which reads data from the server and, for cost-saving purpose, needs to store data on the browser so that it can "incrementally" reads data from the server instead of reading them all every time, to reduce network usage.我正在开发一个 web 应用程序,该应用程序从服务器读取数据,为了节省成本,需要将数据存储在浏览器上,以便它可以“增量”从服务器读取数据,而不是每次都读取它们,以减少网络使用。

What I have so far is:到目前为止,我所拥有的是:

  • a function to add an array to an existing object store:一个 function 将数组添加到现有的 object 存储:
function IXDBaddItems(osName, items, callback) {
  const tx = db.transaction([osName], "readwrite");
  const obj = tx.objectStore(osName);

  items.forEach(item => {
    obj.put(item);
  })

  tx.oncomplete = (event) => {
    callback();
  }
};
  • a function that makes incremental ajax call on the server having an argument "lastId", and finally store the results in the objectStore一个 function 在服务器上进行增量 ajax 调用,参数为“lastId”,最后将结果存储在 objectStore
const getCorsiLastId = (lastId) => {
  makeAjaxCall(urlCorsiVendite, "POST", {
      ultimoId: lastId
    })
    .then(
      (resp) => {
        resp.forEach(d => {
          d.id = +d.id;
          d.id_course = +d.id_course;
          d.id_user = +d.id_user;
          d.insert_Date = new Date(d.insert_Date);
          d.nome_corso = d.nome_corso;
          d.year = +d.insert_Date.getFullYear();
          d.month = +d.insert_Date.getMonth() + 1;
          d.ref = +d.ref;
        });
      IXDBaddItems('corsiVendite', resp, () => console.log('db corsi update completed'));
      },
      (err) => console.log(err)
    );
};
  • the "async main body": “异步主体”:
let db;

(async () => {
  let request = window.indexedDB.open('dbKpiMarketing', 1);

  // onerror handler signifies that the database didn't open successfully
  request.onerror = (e) => {
    console.log(e);
  };

  // onsuccess handler signifies that the database opened successfully
  request.onsuccess = async(e) => {
    console.log('Database opened successfully');

    // Store the opened database object in the db variable. This is used a lot below
    db = request.result;

    getCorsiLastId(0);
  };

  // Setup the database tables if this has not already been done
  request.onupgradeneeded = (e) => {
    // Grab a reference to the opened database
    let db = e.target.result;

    // Create an objectStore to store our data
    let osCorsi = db.createObjectStore('corsiVendite', {
      keyPath: 'id'
    });
    let osServizi = db.createObjectStore('serviziVendite', {
      keyPath: 'id'
    });

    console.log('Database setup complete');
  };

})();

Right now I'm calling the ajax function with lastId=0 to get everything back.现在我用 lastId=0 调用 ajax function 来取回所有东西。 I need to make this dynamic.我需要使这个动态。 With these two lines of code in console i get what i'm looking for: the highest stored id.通过控制台中的这两行代码,我得到了我正在寻找的东西:最高存储的 id。

let c = db.transaction('corsiVendite').objectStore('corsiVendite').getAll()
let lastIdCorsi = Math.max(...c.result.map(d=>d.id));

I need to take these two lines and run them before calling getCorsiLastId(LastIdCorsi) but if i try that I get an error: Uncaught (in promise) DOMException: Failed to read the 'result' property from 'IDBRequest': The request has not finished.我需要在调用getCorsiLastId(LastIdCorsi)之前获取这两行并运行它们但是如果我尝试我得到一个错误: Uncaught (in promise) DOMException: Failed to read the 'result' property from 'IDBRequest': The request has not完成的。 I understand that the transaction takes some time so I can't use the result right after.我知道交易需要一些时间,所以我不能立即使用结果。 How can I overcome this issue?我该如何克服这个问题?

I think I solved it...I actually already did the right thing in the IXDBaddItems function using the oncomplete method of the transaction.我想我解决了...实际上我已经使用事务的oncomplete方法在 IXDBaddItems function 中做了正确的事情。 I added these lines:我添加了这些行:

let t = db.transaction('corsiVendite', 'readwrite');
let o = t.objectStore('corsiVendite');
let c = o.getAll();
t.oncomplete = (e) => {
    LastId = Math.max(...c.result.map(d=>d.id));
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM