From 8bd68e0f107cc241c17ea02b8a2eeeb3fcbc3ecf Mon Sep 17 00:00:00 2001 From: David Baker Date: Fri, 9 Mar 2018 16:53:27 +0000 Subject: [PATCH] Create indexeddb worker when starting the store Rather than when creating it, otherwise we could potentially end up starting workers unnecessarily. --- src/store/indexeddb-remote-backend.js | 29 ++++++++++++++++++--------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/store/indexeddb-remote-backend.js b/src/store/indexeddb-remote-backend.js index e5c1cdd84..2221377db 100644 --- a/src/store/indexeddb-remote-backend.js +++ b/src/store/indexeddb-remote-backend.js @@ -31,20 +31,16 @@ import Promise from 'bluebird'; const RemoteIndexedDBStoreBackend = function RemoteIndexedDBStoreBackend( workerScript, dbName, WorkerApi, ) { + this._workerScript = workerScript; this._dbName = dbName; - this._worker = new WorkerApi(workerScript); + this._workerApi = WorkerApi; + this._worker = null; this._nextSeq = 0; // The currently in-flight requests to the actual backend this._inFlight = { // seq: promise, }; - - this._worker.onmessage = this._onWorkerMessage.bind(this); - - // tell the worker the db name. - this._startPromise = this._doCmd('_setupWorker', [this._dbName]).then(() => { - console.log("IndexedDB worker is ready"); - }); + this._startPromise = null; }; @@ -55,7 +51,7 @@ RemoteIndexedDBStoreBackend.prototype = { * @return {Promise} Resolves if successfully connected. */ connect: function() { - return this._startPromise.then(() => this._doCmd('connect')); + return this._ensureStarted().then(() => this._doCmd('connect')); }, /** @@ -64,7 +60,7 @@ RemoteIndexedDBStoreBackend.prototype = { * @return {Promise} Resolved when the database is cleared. */ clearDatabase: function() { - return this._startPromise.then(() => this._doCmd('clearDatabase')); + return this._ensureStarted().then(() => this._doCmd('clearDatabase')); }, /** @@ -93,6 +89,19 @@ RemoteIndexedDBStoreBackend.prototype = { return this._doCmd('getUserPresenceEvents'); }, + _ensureStarted: function() { + if (this._startPromise === null) { + this._worker = new this._workerApi(this._workerScript); + this._worker.onmessage = this._onWorkerMessage.bind(this); + + // tell the worker the db name. + this._startPromise = this._doCmd('_setupWorker', [this._dbName]).then(() => { + console.log("IndexedDB worker is ready"); + }); + } + return this._startPromise; + }, + _doCmd: function(cmd, args) { // wrap in a q so if the postMessage throws, // the promise automatically gets rejected