Как загрузить файл stati c json ТОЛЬКО в indexedDB, когда требуется обновление (то есть onupgradeneeded) - PullRequest
0 голосов
/ 21 марта 2020

Я пытаюсь загрузить файл stati c json в indexedDB ТОЛЬКО, когда требуется обновление (т.е. onupgradeneeded). Я неоднократно искал ответы на этот вопрос, но пока не видел примеров кода того, как подойти к этому.

Мой текущий код ниже получает файл json при каждом открытии страницы, что, конечно, неэффективно, поскольку мне нужно получить файл json, только если indexedDB еще не создан или нуждается в обновлении.

Я попытался поместить раздел xhr.onload в конец функции .onupgradeneeded, но, как отмечали многие, .onsuccess вызывается до завершения xhr.onload.

var jsonUrl = '/path/to/hcLookup.json');

var req, db, hcObjectStore, objectStore, data, dataArr, trans, addreq, key;


var xhr = new XMLHttpRequest();
xhr.open("GET", jsonUrl, true);
xhr.type='json';
xhr.send();
xhr.onload = function(msg) {
  data = msg.target.response;

  req = window.indexedDB.open("hcLookup", 1);
  req.onerror=function(event){console.log("onerror: " + event.target.errorCode)};
  req.onsuccess = function(event){
    console.log("ready.");
  };
  req.onupgradeneeded = function(event){
    db = event.target.result;

    objectStore = db.createObjectStore("hcLookup", {autoIncrement: true});
    objectStore.createIndex("S", "S", {unique: false});

    // make sure the objectStore creation is finished before adding data into it
    objectStore.transaction.oncomplete = function (event) {
      // Store values in the newly created objectStore.
      trans = db.transaction(["hcLookup"], "readwrite");
      hcObjectStore = trans.objectStore("hcLookup");
      // Do something when all the data is added to the database.
      trans.oncomplete = function (event) {
        console.log("upgrading done!");
      };
      trans.onerror = function (event) {
        console.log("bulk add onerror: " + event.target.errorCode)
      };

      //convert JSON to an strArray in order to add the dataArr into to the objectStore
      dataArr = JSON.parse(data);
      for (var i in dataArr) {
        addreq = hcObjectStore.add(dataArr[i]);
      }
    };
  };
};
...