Skip to content

Instantly share code, notes, and snippets.

@nonlogos
Last active November 21, 2017 15:53
Show Gist options
  • Select an option

  • Save nonlogos/145c548d1c42103a6b3737239daad093 to your computer and use it in GitHub Desktop.

Select an option

Save nonlogos/145c548d1c42103a6b3737239daad093 to your computer and use it in GitHub Desktop.
IndexDB
const dbPromise = idb.open('post-store', 1, function(db) {
if (!db.objectStoreNames.contains('posts')) {
db.createObjectStore('posts', {keyPath: 'id'});
}
});
// service worker implementation
...
event.respondWith(fetch(event.request)
.then(res => {
const clonedRes = res.clone();
cloneRes.json()
.then(data => {
for (let key in data) {
dbPromise
.then(db => {
const tx = db.transaction('posts', 'readwrite');
const store = tx.objectStore('posts');
store.put(data[key]);
return tx.complete;
})
}
});
return res;
})
);
// or set up it's own indexdb file
const dbPromise = idb.open('post-store', 1, function(db) {
if (!db.objectStoreNames.contains('posts')) {
db.createObjectStore('posts', {keyPath: 'id'});
}
});
function writeData(store, data) {
return dbPromise
.then(db => {
const tx = db.transaction(store, 'readwrite');
const store = tx.objectStore(store);
store.put(data);
return tx.complete;
});
}
function readAllData(store) {
return dbPromise
.then(db => {
const tx = db.transaction(store, 'readonly');
const store = tx.objectStore(store);
return store.getAll(); // don't need tx.complete
});
}
if ('indexedDB' in window) {
readAllData('post')
.then(data => {
if (!networkDataReceived) {
console.log('from cache', data);
updateUI(data);
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment