aboutsummaryrefslogtreecommitdiff
path: root/node_modules/workbox-core/_private/DBWrapper.mjs
blob: 61def037777db972ab6c2300a20c120de42b9c84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*
  Copyright 2017 Google Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

import '../_version.mjs';

/**
 * A class that wraps common IndexedDB functionality in a promise-based API.
 * It exposes all the underlying power and functionality of IndexedDB, but
 * wraps the most commonly used features in a way that's much simpler to use.
 *
 * @private
 */
class DBWrapper {
  /**
   * @param {string} name
   * @param {number} version
   * @param {Object=} [callback]
   * @param {function(this:DBWrapper, Event)} [callbacks.onupgradeneeded]
   * @param {function(this:DBWrapper, Event)} [callbacks.onversionchange]
   *     Defaults to DBWrapper.prototype._onversionchange when not specified.
   */
  constructor(name, version, {
    onupgradeneeded,
    onversionchange = this._onversionchange,
  } = {}) {
    this._name = name;
    this._version = version;
    this._onupgradeneeded = onupgradeneeded;
    this._onversionchange = onversionchange;

    // If this is null, it means the database isn't open.
    this._db = null;
  }

  /**
   * Opens a connected to an IDBDatabase, invokes any onupgradedneeded
   * callback, and added an onversionchange callback to the database.
   *
   * @return {IDBDatabase}
   *
   * @private
   */
  async open() {
    if (this._db) return;

    this._db = await new Promise((resolve, reject) => {
      // This flag is flipped to true if the timeout callback runs prior
      // to the request failing or succeeding. Note: we use a timeout instead
      // of an onblocked handler since there are cases where onblocked will
      // never never run. A timeout better handles all possible scenarios:
      // https://github.com/w3c/IndexedDB/issues/223
      let openRequestTimedOut = false;
      setTimeout(() => {
        openRequestTimedOut = true;
        reject(new Error('The open request was blocked and timed out'));
      }, this.OPEN_TIMEOUT);

      const openRequest = indexedDB.open(this._name, this._version);
      openRequest.onerror = (evt) => reject(openRequest.error);
      openRequest.onupgradeneeded = (evt) => {
        if (openRequestTimedOut) {
          openRequest.transaction.abort();
          evt.target.result.close();
        } else if (this._onupgradeneeded) {
          this._onupgradeneeded(evt);
        }
      };
      openRequest.onsuccess = (evt) => {
        const db = evt.target.result;
        if (openRequestTimedOut) {
          db.close();
        } else {
          db.onversionchange = this._onversionchange;
          resolve(db);
        }
      };
    });

    return this;
  }

  /**
   * Delegates to the native `get()` method for the object store.
   *
   * @param {string} storeName The name of the object store to put the value.
   * @param {...*} args The values passed to the delegated method.
   * @return {*} The key of the entry.
   *
   * @private
   */
  async get(storeName, ...args) {
    return await this._call('get', storeName, 'readonly', ...args);
  }

  /**
   * Delegates to the native `add()` method for the object store.
   *
   * @param {string} storeName The name of the object store to put the value.
   * @param {...*} args The values passed to the delegated method.
   * @return {*} The key of the entry.
   *
   * @private
   */
  async add(storeName, ...args) {
    return await this._call('add', storeName, 'readwrite', ...args);
  }

  /**
   * Delegates to the native `put()` method for the object store.
   *
   * @param {string} storeName The name of the object store to put the value.
   * @param {...*} args The values passed to the delegated method.
   * @return {*} The key of the entry.
   *
   * @private
   */
  async put(storeName, ...args) {
    return await this._call('put', storeName, 'readwrite', ...args);
  }

  /**
   * Delegates to the native `delete()` method for the object store.
   *
   * @param {string} storeName
   * @param {...*} args The values passed to the delegated method.
   *
   * @private
   */
  async delete(storeName, ...args) {
    await this._call('delete', storeName, 'readwrite', ...args);
  }

  /**
   * Deletes the underlying database, ensuring that any open connections are
   * closed first.
   *
   * @private
   */
  async deleteDatabase() {
    this.close();
    this._db = null;
    await new Promise((resolve, reject) => {
      const request = indexedDB.deleteDatabase(this._name);
      request.onerror = (evt) => reject(evt.target.error);
      request.onblocked = () => reject(new Error('Deletion was blocked.'));
      request.onsuccess = () => resolve();
    });
  }

  /**
   * Delegates to the native `getAll()` or polyfills it via the `find()`
   * method in older browsers.
   *
   * @param {string} storeName
   * @param {*} query
   * @param {number} count
   * @return {Array}
   *
   * @private
   */
  async getAll(storeName, query, count) {
    if ('getAll' in IDBObjectStore.prototype) {
      return await this._call('getAll', storeName, 'readonly', query, count);
    } else {
      return await this.getAllMatching(storeName, {query, count});
    }
  }

  /**
   * Supports flexible lookup in an object store by specifying an index,
   * query, direction, and count. This method returns an array of objects
   * with the signature .
   *
   * @param {string} storeName
   * @param {Object} [opts]
   * @param {IDBCursorDirection} [opts.direction]
   * @param {*} [opts.query]
   * @param {string} [opts.index] The index to use (if specified).
   * @param {number} [opts.count] The max number of results to return.
   * @param {boolean} [opts.includeKeys] When true, the structure of the
   *     returned objects is changed from an array of values to an array of
   *     objects in the form {key, primaryKey, value}.
   * @return {Array}
   *
   * @private
   */
  async getAllMatching(storeName, opts = {}) {
    return await this.transaction([storeName], 'readonly', (stores, done) => {
      const store = stores[storeName];
      const target = opts.index ? store.index(opts.index) : store;
      const results = [];

      // Passing `undefined` arguments to Edge's `openCursor(...)` causes
      // 'DOMException: DataError'
      // Details in issue: https://github.com/GoogleChrome/workbox/issues/1509
      const query = opts.query || null;
      const direction = opts.direction || 'next';
      target.openCursor(query, direction).onsuccess = (evt) => {
        const cursor = evt.target.result;
        if (cursor) {
          const {primaryKey, key, value} = cursor;
          results.push(opts.includeKeys ? {primaryKey, key, value} : value);
          if (opts.count && results.length >= opts.count) {
            done(results);
          } else {
            cursor.continue();
          }
        } else {
          done(results);
        }
      };
    });
  }

  /**
   * Accepts a list of stores, a transaction type, and a callback and
   * performs a transaction. A promise is returned that resolves to whatever
   * value the callback chooses. The callback holds all the transaction logic
   * and is invoked with three arguments:
   *   1. An object mapping object store names to IDBObjectStore values.
   *   2. A `done` function, that's used to resolve the promise when
   *      when the transaction is done.
   *   3. An `abort` function that can be called to abort the transaction
   *      at any time.
   *
   * @param {Array<string>} storeNames An array of object store names
   *     involved in the transaction.
   * @param {string} type Can be `readonly` or `readwrite`.
   * @param {function(Object, function(), function(*)):?IDBRequest} callback
   * @return {*} The result of the transaction ran by the callback.
   *
   * @private
   */
  async transaction(storeNames, type, callback) {
    await this.open();
    const result = await new Promise((resolve, reject) => {
      const txn = this._db.transaction(storeNames, type);
      const done = (value) => resolve(value);
      const abort = () => {
        reject(new Error('The transaction was manually aborted'));
        txn.abort();
      };
      txn.onerror = (evt) => reject(evt.target.error);
      txn.onabort = (evt) => reject(evt.target.error);
      txn.oncomplete = () => resolve();

      const stores = {};
      for (const storeName of storeNames) {
        stores[storeName] = txn.objectStore(storeName);
      }
      callback(stores, done, abort);
    });
    return result;
  }

  /**
   * Delegates async to a native IDBObjectStore method.
   *
   * @param {string} method The method name.
   * @param {string} storeName The object store name.
   * @param {string} type Can be `readonly` or `readwrite`.
   * @param {...*} args The list of args to pass to the native method.
   * @return {*} The result of the transaction.
   *
   * @private
   */
  async _call(method, storeName, type, ...args) {
    await this.open();
    const callback = (stores, done) => {
      stores[storeName][method](...args).onsuccess = (evt) => {
        done(evt.target.result);
      };
    };

    return await this.transaction([storeName], type, callback);
  }

  /**
   * The default onversionchange handler, which closes the database so other
   * connections can open without being blocked.
   *
   * @param {Event} evt
   *
   * @private
   */
  _onversionchange(evt) {
    this.close();
  }

  /**
   * Closes the connection opened by `DBWrapper.open()`. Generally this method
   * doesn't need to be called since:
   *   1. It's usually better to keep a connection open since opening
   *      a new connection is somewhat slow.
   *   2. Connections are automatically closed when the reference is
   *      garbage collected.
   * The primary use case for needing to close a connection is when another
   * reference (typically in another tab) needs to upgrade it and would be
   * blocked by the current, open connection.
   *
   * @private
   */
  close() {
    if (this._db) this._db.close();
  }
}

// Exposed to let users modify the default timeout on a per-instance
// or global basis.
DBWrapper.prototype.OPEN_TIMEOUT = 2000;

export {DBWrapper};