[PWA] 12. Intro to IndexedDB

Use the library indexedDB-promised.

 

Create a database and stroe:

import idb from 'idb';

// Open(db_name, version, cb)
var dbPromise = idb.open('test-db', 1, function (upgradeDb) {
    var keyValStore = upgradeDb.createObjectStore('keyval'); // create table
    //put(value, key)
    keyValStore.put('world', 'Hello');
});

Notice put() function take value frist then key.

 

Read the key in stroe:

// read "hello" in "keyval"
dbPromise.then(function (db) {
    var tx = db.transaction('keyval'); // Open a transaction
    var keyValStore = tx.objectStore('keyval'); // read the store
    return keyValStore.get('hello'); // get value by key
}).then(function (val) {
    console.log('The value of "hello" is:', val);
});

 

Write value to store:

// set "foo" to be "bar" in "keyval"
dbPromise.then(function (db) {
    var tx = db.transaction('keyval', 'readwrite'); // ready for add key value
    var keyValStore = tx.objectStore('keyval'); // get the store
    keyValStore.put('bar', 'foo'); // set the value, notice it may not be success if any step in transaction fail.
    return tx.complete; // tx.complete is a promise
}).then(function () {
    console.log('Added foo:bar to keyval');
});

 

 

posted @ 2016-05-18 03:41  Zhentiw  阅读(211)  评论(0编辑  收藏  举报