Last active
November 21, 2017 15:53
-
-
Save nonlogos/145c548d1c42103a6b3737239daad093 to your computer and use it in GitHub Desktop.
IndexDB
This file contains hidden or 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
| 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 | |
| }); | |
| } |
This file contains hidden or 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
| 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