Last active
March 8, 2018 11:23
-
-
Save amitasaurus/a2877184dbc53e36120f410b5173bd5f to your computer and use it in GitHub Desktop.
IndexedDB with Jake Archibald's IDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import idb from 'idb'; | |
var dbPromise = idb.open('test-db', 1, function(upgradeDb) { | |
switch (upgradeDb.oldVersion) { | |
case 0: | |
upgradeDb.createObjectStore('keyval'); | |
case 1: | |
//name would be the primary key | |
upgradeDb.createObjectStore('people', { | |
keyPath: 'name' | |
}); | |
case 2: | |
//creating index with city | |
var peopleStore = upgradeDb.transaction.objectStore('people'); | |
peopleStore.createIndex('place', 'city'); | |
case 3: | |
//creating index with age | |
var peopleStore = upgradeDb.transaction.objectStore('people'); | |
peopleStore.createIndex('age', 'age'); | |
} | |
}); | |
dbPromise.then(function(db) { | |
var tx = db.transaction('keyval', 'readwrite'); | |
var keyValStore = tx.objectStore('keyval'); | |
keyValStore.put('bar', 'foo'); | |
return tx.complete; | |
}).then(function() { | |
console.log('Added foo:bar to keyval'); | |
}); | |
dbPromise.then(function(db) { | |
const tx = db.transaction('keyval', 'readwrite'); | |
const keyValStore = tx.objectStore('keyval'); | |
keyValStore.put('dog', 'favoriteAnimal'); | |
return tx.complete; | |
}) | |
.then((val) => { | |
console.log('Successfully added to favoriteAnimal'); | |
}); | |
dbPromise.then((db) => { | |
const tx = db.transaction('people', 'readwrite'); | |
const peopleStore = tx.objectStore('people'); | |
peopleStore.put({ | |
name: 'Amit', | |
age: 22, | |
city: 'Bangalore' | |
}); | |
peopleStore.put({ | |
name: 'Harshit', | |
age: 22, | |
city: 'Delhi' | |
}); | |
peopleStore.put({ | |
name: 'Amrita', | |
age: 29, | |
city: 'Agra' | |
}); | |
return tx.complete; | |
}) | |
dbPromise.then((db) => { | |
const tx = db.transaction('people'); | |
const peopleStore = tx.objectStore('people'); | |
const cityIndex = peopleStore.index('place'); | |
const ageIndex = peopleStore.index('age'); | |
//peopleStore.getAll() would return result ordered by name | |
//cityIndex.getAll() would return result ordered by city | |
//ageIndex.getAll() would return result ordered by age | |
return ageIndex.getAll() | |
}).then((people) => { | |
console.log(people); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://youtu.be/vCumk1sXHcY
https://developers.google.com/web/ilt/pwa/working-with-indexeddb
https://github.com/jakearchibald/idb/blob/master/README.md