indexdbwrapper.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. class IndexDBWrapper {
  2. constructor(
  3. name,
  4. version,
  5. { onupgradeneeded, onversionchange = this._onversionchange } = {}
  6. ) {
  7. this._name = name;
  8. this._version = version;
  9. this._onupgradeneeded = onupgradeneeded;
  10. this._onversionchange = onversionchange;
  11. this._db = null;
  12. }
  13. get db() {
  14. return this._db;
  15. }
  16. async open() {
  17. if (this._db) return;
  18. this._db = await new Promise((resolve, reject) => {
  19. let openRequestTimedOut = false;
  20. setTimeout(() => {
  21. openRequestTimedOut = true;
  22. reject(new Error("The open request was blocked and timed out"));
  23. }, this.OPEN_TIMEOUT);
  24. const openRequest = indexedDB.open(this._name, this._version);
  25. openRequest.onerror = () => reject(openRequest.error);
  26. openRequest.onupgradeneeded = evt => {
  27. if (openRequestTimedOut) {
  28. openRequest.transaction.abort();
  29. evt.target.result.close();
  30. } else if (this._onupgradeneeded) {
  31. this._onupgradeneeded(evt);
  32. }
  33. };
  34. openRequest.onsuccess = ({ target }) => {
  35. const db = target.result;
  36. if (openRequestTimedOut) {
  37. db.close();
  38. } else {
  39. db.onversionchange = this._onversionchange.bind(this);
  40. resolve(db);
  41. }
  42. };
  43. });
  44. return this;
  45. }
  46. async getKey(storeName, query) {
  47. return (await this.getAllKeys(storeName, query, 1))[0];
  48. }
  49. async getAll(storeName, query, count) {
  50. return await this.getAllMatching(storeName, {
  51. query,
  52. count
  53. });
  54. }
  55. async getAllKeys(storeName, query, count) {
  56. return (await this.getAllMatching(storeName, {
  57. query,
  58. count,
  59. includeKeys: true
  60. })).map(({ key }) => key);
  61. }
  62. async getAllMatching(
  63. storeName,
  64. { index, query = null, direction = "next", count, includeKeys } = {}
  65. ) {
  66. return await this.transaction([storeName], "readonly", (txn, done) => {
  67. const store = txn.objectStore(storeName);
  68. const target = index ? store.index(index) : store;
  69. const results = [];
  70. target.openCursor(query, direction).onsuccess = ({ target }) => {
  71. const cursor = target.result;
  72. if (cursor) {
  73. const { primaryKey, key, value } = cursor;
  74. results.push(
  75. includeKeys
  76. ? {
  77. primaryKey,
  78. key,
  79. value
  80. }
  81. : value
  82. );
  83. if (count && results.length >= count) {
  84. done(results);
  85. } else {
  86. cursor.continue();
  87. }
  88. } else {
  89. done(results);
  90. }
  91. };
  92. });
  93. }
  94. async transaction(storeNames, type, callback) {
  95. await this.open();
  96. return await new Promise((resolve, reject) => {
  97. const txn = this._db.transaction(storeNames, type);
  98. txn.onabort = ({ target }) => reject(target.error);
  99. txn.oncomplete = () => resolve();
  100. callback(txn, value => resolve(value));
  101. });
  102. }
  103. async _call(method, storeName, type, ...args) {
  104. const callback = (txn, done) => {
  105. txn.objectStore(storeName)[method](...args).onsuccess = ({ target }) => {
  106. done(target.result);
  107. };
  108. };
  109. return await this.transaction([storeName], type, callback);
  110. }
  111. _onversionchange() {
  112. this.close();
  113. }
  114. close() {
  115. if (this._db) {
  116. this._db.close();
  117. this._db = null;
  118. }
  119. }
  120. static async deleteDatabase(name) {
  121. await new Promise((resolve, reject) => {
  122. const request = indexedDB.deleteDatabase(name);
  123. request.onerror = ({ target }) => {
  124. reject(target.error);
  125. };
  126. request.onblocked = () => {
  127. reject(new Error("Delete blocked"));
  128. };
  129. request.onsuccess = () => {
  130. resolve();
  131. };
  132. });
  133. }
  134. }
  135. IndexDBWrapper.prototype.OPEN_TIMEOUT = 2000;
  136. (function() {
  137. const methodsToWrap = {
  138. readonly: ["get", "count", "getKey", "getAll", "getAllKeys"],
  139. readwrite: ["add", "put", "clear", "delete"]
  140. };
  141. for (const [mode, methods] of Object.entries(methodsToWrap)) {
  142. for (const method of methods) {
  143. if (method in IDBObjectStore.prototype) {
  144. IndexDBWrapper.prototype[method] = async function(storeName, ...args) {
  145. return await this._call(method, storeName, mode, ...args);
  146. };
  147. }
  148. }
  149. }
  150. })();