import idb from 'idb';
var dbPromise = idb.open('test-db', 4, function (upgradeDb) {
switch (upgradeDb.oldVersion) {
case 0:
// keyval store is already created at version 1
var keyValStore = upgradeDb.createObjectStore('keyval');
keyValStore.put("world", "hello");
case 1:
// new version
upgradeDb.createObjectStore('people', {keyPath: 'name'});
case 2:
var peopleStore = upgradeDb.transaction.objectStore('people');
peopleStore.createIndex('animal', 'favoriteAnimal');
case 3:
var peopleStore = upgradeDb.transaction.objectStore('people');
peopleStore.createIndex('age', 'age');
}
});
// 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);
});
dbPromise.then(function (db) {
var tx = db.transaction('people', 'readwrite');
var peopleStore = tx.objectStore('people');
peopleStore.put({
name: "John", // name is the key
age: 23,
favoriteAnimal: 'cat'
});
peopleStore.put({
name: "Joe", // name is the key
age: 21,
favoriteAnimal: 'cat'
});
peopleStore.put({
name: "Jie", // name is the key
age: 22,
favoriteAnimal: 'dog'
});
peopleStore.put({
name: "Jay", // name is the key
age: 24,
favoriteAnimal: 'dog'
});
return tx.complete;
}).then(function () {
console.log("People are added");
});
dbPromise.then(function (db) {
var tx = db.transaction('people', 'readwrite');
var peopleStore = tx.objectStore('people');
var ageIndex = peopleStore.index('age');
return ageIndex.openCursor();
}).then(function (cursor) {
if (!cursor) return;
return cursor.advance(1); // skip the first person
}).then(function logPerson(cursor) {
if(cursor.value.name == "Jie"){
cursor.delete(); // delete
}
if(cursor.value.name == "Jay"){
console.log("Cursor at:", cursor.value.name);
var joe = cursor.value;
joe.favoriteAnimal = "Bird";
cursor.update(joe); // update
}
return cursor.continue().then(logPerson);
}).then(function () {
console.log("DONE");
});