IndexedDB Cheatsheet

打开数据库:


let dbPromise = indexDB.open('db-name', 1 /* version */, db => {

    // db operations here

});

增加API:


let transaction = db.transaction(['blogs'],'readwrite');
transaction.oncomplete = (event) => {
  console.log('Success');
};
transaction.onerror = (event) => {
  console.log('Error');
};
let objectStore = transaction.objectStore('blogs');
objectStore.add({rollNo: rollNo, name: name});

删除API:


db.transaction(['blogs'],'readwrite').objectStore('blogs').delete(rollNo);

修改API:


let transaction = db.transaction(['blogs'],'readwrite');
let objectStore = transaction.objectStore('blogs');
let request = objectStore.get(rollNo);
request.onsuccess = (event) => {
  console.log(`Updating : ${request.result.name}`);
  request.result.name = name;
  objectStore.put(request.result);
};

查询API:


let request = db.transaction(['blogs'],'readwrite').objectStore('blogs').get(rollNo);
request.onsuccess = (event) => {
  console.log(`Name : ${request.result.name}`);
};

还有一种写法是这样的:


dbPromise.then(function(db) {
  var tx = db.transaction('store', 'readwrite');
  var store = tx.objectStore('store');
  var item = {
    name: 'sandwich',
    price: 4.99,
    description: 'A very tasty sandwich',
    created: new Date().getTime()
  };
  store.add(item);
  return tx.complete;
}).then(function() {
  console.log('added item to the store os!');
});

可以看到这个API非常的抽象,是真的抽象。

我们考虑使用一些wrapper来简化操作。

https://dexie.org/ dexieDB,高级封装。

https://github.com/jakearchibald/idb iDB,Promisify。