We want to use IDB to store the wittr messages.
The logic is when the page start:
- Service worker would read the skeleton from the cache and show to the interface.
- Read the message data from the IDB first instead by going to network.
- Show the data from IDB then open socket to fetch updated wittr.
- Once data arrive, update the interface and save into IDB.
Exportdefault functionIndexcontroller (container) { This. _container =container; This. _postsview =NewPostsview ( This. _container); This. _toastsview =NewToastsview ( This. _container); This. _lostconnectiontoast =NULL; This . _opensocket (); this. _dbpromise = OpenDatabase (); This . _registerserviceworker ();}
In OpenDatabase (), we create WITTR DB, set ID as primary key and time as index called ' By-time '
function OpenDatabase () { // If The browser doesn ' t support Service worker, // We don ' t care on having a database if (! Navigator.serviceworker) { return promise.resolve (); } return function (upgradedb) { = Upgradedb.createobjectstore (' wittrs ', { ' id ' }); Store.createindex (' by-date ', ' time '); });
In _opensocket, we had a function to fetch the old data from the IDB.
// Open a connection to the server for live updates function () {
... Ws.addeventlistener (function(event) { requestanimationframe() { Indexcontroller. _onsocketmessage (event.data); }); ...};
//called when the Web socket sends message dataIndexcontroller.prototype._onsocketmessage =function(data) {varMessages =json.parse (data); This. _dbpromise.then (function(db) {if(!DB)return; //todo:put each message into the ' Wittrs ' //Object store.CONST TX = db.transaction (' wittrs ', ' ReadWrite '); Const WITTRS= Tx.objectstore (' Wittrs '); Messages.foreach (message)={wittrs.put (message); }); returnTx.complete; }); This. _postsview.addposts (messages);};
[PWA] 15. Using the IDB Cache and Display Entries