Source: lib/offline/indexeddb/db_connection.js

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