Source: lib/offline/indexeddb/db_connection.js

  1. /** @license
  2. * Copyright 2016 Google LLC
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. goog.provide('shaka.offline.indexeddb.DBConnection');
  6. goog.require('shaka.offline.indexeddb.DBOperation');
  7. goog.require('shaka.util.ArrayUtils');
  8. /**
  9. * DBConnection is used to manage an IndexedDB connection. It can create new
  10. * operations. If the connection is killed (via |destroy|) all pending
  11. * operations will be cancelled.
  12. */
  13. shaka.offline.indexeddb.DBConnection = class {
  14. /**
  15. * @param {IDBDatabase} connection A connection to an IndexedDB instance.
  16. */
  17. constructor(connection) {
  18. /** @private {IDBDatabase} */
  19. this.connection_ = connection;
  20. /** @private {!Array.<shaka.offline.indexeddb.DBOperation>} */
  21. this.pending_ = [];
  22. }
  23. /**
  24. * @return {!Promise}
  25. */
  26. destroy() {
  27. return Promise.all(this.pending_.map((op) => {
  28. return op.abort();
  29. }));
  30. }
  31. /**
  32. * @param {string} store The name of the store that the operation should
  33. * occur on.
  34. * @return {!shaka.offline.indexeddb.DBOperation}
  35. */
  36. startReadOnlyOperation(store) {
  37. return this.startOperation_(store, 'readonly');
  38. }
  39. /**
  40. * @param {string} store The name of the store that the operation should
  41. * occur on.
  42. * @return {!shaka.offline.indexeddb.DBOperation}
  43. */
  44. startReadWriteOperation(store) {
  45. return this.startOperation_(store, 'readwrite');
  46. }
  47. /**
  48. * @param {string} store The name of the store that the operation should
  49. * occur on.
  50. * @param {string} type The type of operation being performed on the store.
  51. * This determines what commands may be performed. This
  52. * can either be "readonly" or "readwrite".
  53. * @return {!shaka.offline.indexeddb.DBOperation}
  54. * @private
  55. */
  56. startOperation_(store, type) {
  57. const transaction = this.connection_.transaction([store], type);
  58. const operation =
  59. new shaka.offline.indexeddb.DBOperation(transaction, store);
  60. this.pending_.push(operation);
  61. // Once the operation is done (regardless of outcome) stop tracking it.
  62. operation.promise().then(
  63. () => this.stopTracking_(operation),
  64. () => this.stopTracking_(operation)
  65. );
  66. return operation;
  67. }
  68. /**
  69. * @param {!shaka.offline.indexeddb.DBOperation} operation
  70. * @private
  71. */
  72. stopTracking_(operation) {
  73. shaka.util.ArrayUtils.remove(this.pending_, operation);
  74. }
  75. };