Advertisement
Guest User

Untitled

a guest
Jan 26th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function openDatabase() {
  2.   // If the browser doesn't support service worker,
  3.   // we don't care about having a database
  4.   if (!navigator.serviceWorker) {
  5.     return Promise.resolve();
  6.   }
  7.  
  8.   // TODO: return a promise for a database called 'wittr'
  9.   // that contains one objectStore: 'wittrs'
  10.   // that uses 'id' as its key
  11.   // and has an index called 'by-date', which is sorted
  12.   // by the 'time' property
  13.   return idb.open('wittr', 1, function(upgradeDb) {
  14.     switch(upgradeDb.oldVersion) {
  15.       case 0:
  16.         var wittrStore = upgradeDb.createObjectStore('wittrs', { keyPath: 'id' });
  17.         wittrStore.createIndex("by-date", 'time');
  18.     }
  19.   });
  20. }
  21.  
  22. // called when the web socket sends message data
  23. IndexController.prototype._onSocketMessage = function(data) {
  24.   var messages = JSON.parse(data);
  25.  
  26.   this._dbPromise.then(function(db) {
  27.     if (!db) return;
  28.  
  29.     // TODO: put each message into the 'wittrs'
  30.     // object store.
  31.     var tx = db.transaction('wittr', 'readwrite');
  32.     var wittrStore = tx.objectStore('wittrs');
  33.     messages.forEach(function(msg) {
  34.       wittrStore.put(msg);
  35.     });
  36.     return tx.complete;
  37.   }).then(function() {
  38.     console.log('New messages added!');
  39.   });
  40.  
  41.   this._postsView.addPosts(messages);
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement