Skip to content

Instantly share code, notes, and snippets.

@luke-denton-aligent
Last active November 16, 2016 04:01
Show Gist options
  • Save luke-denton-aligent/193fd42e9fcfe6e2f1e8b6c4de58dc4e to your computer and use it in GitHub Desktop.
Save luke-denton-aligent/193fd42e9fcfe6e2f1e8b6c4de58dc4e to your computer and use it in GitHub Desktop.
These snippets show how to work with putting objects into the IndexedDB database, not just simple string key/values
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
//This should all go into an indexed-db index.js file
//Again, idb is a plugin used to make working with IndexedDB easier
//Difference between this and https://gist.github.com/luke-denton/55be283cbddf6f0c0d362fd95fc9280a, version has been upgraded
var dbPromise = idb.open('test-db', 2, function() {
switch(upgradeDb.oldVersion)
case 0:
var keyValStore = upgradeDb.createObjectStore('keyval');
keyValStore.put("world", "hello");
//No break; here, so that if a user comes with a much older database, they'll get all updates in order.
//Or, if they only need the very newest one, they'll jump straight to that point in the code
case 1:
upgradeDb.createObjectStore('people', { keypath: 'name' });
case 2:
//For grouping together using indexes
var peopleStore = upgradeDb.transaction.objectStore('people');
peopleStore.createIndex('superhero', 'favoriteSuperhero');
})
//Add some data to the new object store
dbPromise.then(function(db) {
var tx = db.transaction('people', 'readwrite');
var peopleStore = tv.objectStore('people');
peopleStore.put({
name: 'Suzanne Norman',
age: 25,
favoriteSuperhero: 'wonder woman'
});
return tx.complete
}).then(function() {
console.log("People added!");
});
//Read data from the datastore
dbPromise.then(function(db) {
var tx = db.transaction('people');
var peopleStore = tx.objectStore('people');
return peopleStore.getAll();
}).then(function(people) {
console.log(people);
});
//Group data together using indexes
dbPromise.then(function(db) {
var tx = db.transaction('people');
var peopleStore = tx.objectStore('people');
var superheroIndex = peopleStore.index('superhero');
return superheroIndex.getAll();
}).then(function(people) {
console.log(people);
});
//Query the data
//Only get people who's favourite superhero is Superman
dbPromise.then(function(db) {
var tx = db.transaction('people');
var peopleStore = tx.objectStore('people');
var superheroIndex = peopleStore.index('superhero');
return superheroIndex.getAll('superman'); //Pass the filter value into the getAll() function
}).then(function(people) {
console.log(people);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment