indexeddb.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. (function (global, factory) {
  2. if (typeof define === "function" && define.amd) {
  3. define('asyncStorage', ['module', 'exports', '../utils/isIndexedDBValid', '../utils/createBlob', '../utils/idb', '../utils/promise', '../utils/executeCallback', '../utils/executeTwoCallbacks', '../utils/normalizeKey', '../utils/getCallback'], factory);
  4. } else if (typeof exports !== "undefined") {
  5. factory(module, exports, require('../utils/isIndexedDBValid'), require('../utils/createBlob'), require('../utils/idb'), require('../utils/promise'), require('../utils/executeCallback'), require('../utils/executeTwoCallbacks'), require('../utils/normalizeKey'), require('../utils/getCallback'));
  6. } else {
  7. var mod = {
  8. exports: {}
  9. };
  10. factory(mod, mod.exports, global.isIndexedDBValid, global.createBlob, global.idb, global.promise, global.executeCallback, global.executeTwoCallbacks, global.normalizeKey, global.getCallback);
  11. global.asyncStorage = mod.exports;
  12. }
  13. })(this, function (module, exports, _isIndexedDBValid, _createBlob, _idb, _promise, _executeCallback, _executeTwoCallbacks, _normalizeKey, _getCallback) {
  14. 'use strict';
  15. Object.defineProperty(exports, "__esModule", {
  16. value: true
  17. });
  18. var _isIndexedDBValid2 = _interopRequireDefault(_isIndexedDBValid);
  19. var _createBlob2 = _interopRequireDefault(_createBlob);
  20. var _idb2 = _interopRequireDefault(_idb);
  21. var _promise2 = _interopRequireDefault(_promise);
  22. var _executeCallback2 = _interopRequireDefault(_executeCallback);
  23. var _executeTwoCallbacks2 = _interopRequireDefault(_executeTwoCallbacks);
  24. var _normalizeKey2 = _interopRequireDefault(_normalizeKey);
  25. var _getCallback2 = _interopRequireDefault(_getCallback);
  26. function _interopRequireDefault(obj) {
  27. return obj && obj.__esModule ? obj : {
  28. default: obj
  29. };
  30. }
  31. // Some code originally from async_storage.js in
  32. // [Gaia](https://github.com/mozilla-b2g/gaia).
  33. var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
  34. var supportsBlobs = void 0;
  35. var dbContexts = {};
  36. var toString = Object.prototype.toString;
  37. // Transaction Modes
  38. var READ_ONLY = 'readonly';
  39. var READ_WRITE = 'readwrite';
  40. // Transform a binary string to an array buffer, because otherwise
  41. // weird stuff happens when you try to work with the binary string directly.
  42. // It is known.
  43. // From http://stackoverflow.com/questions/14967647/ (continues on next line)
  44. // encode-decode-image-with-base64-breaks-image (2013-04-21)
  45. function _binStringToArrayBuffer(bin) {
  46. var length = bin.length;
  47. var buf = new ArrayBuffer(length);
  48. var arr = new Uint8Array(buf);
  49. for (var i = 0; i < length; i++) {
  50. arr[i] = bin.charCodeAt(i);
  51. }
  52. return buf;
  53. }
  54. //
  55. // Blobs are not supported in all versions of IndexedDB, notably
  56. // Chrome <37 and Android <5. In those versions, storing a blob will throw.
  57. //
  58. // Various other blob bugs exist in Chrome v37-42 (inclusive).
  59. // Detecting them is expensive and confusing to users, and Chrome 37-42
  60. // is at very low usage worldwide, so we do a hacky userAgent check instead.
  61. //
  62. // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
  63. // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
  64. // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
  65. //
  66. // Code borrowed from PouchDB. See:
  67. // https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
  68. //
  69. function _checkBlobSupportWithoutCaching(idb) {
  70. return new _promise2.default(function (resolve) {
  71. var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
  72. var blob = (0, _createBlob2.default)(['']);
  73. txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
  74. txn.onabort = function (e) {
  75. // If the transaction aborts now its due to not being able to
  76. // write to the database, likely due to the disk being full
  77. e.preventDefault();
  78. e.stopPropagation();
  79. resolve(false);
  80. };
  81. txn.oncomplete = function () {
  82. var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
  83. var matchedEdge = navigator.userAgent.match(/Edge\//);
  84. // MS Edge pretends to be Chrome 42:
  85. // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
  86. resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
  87. };
  88. }).catch(function () {
  89. return false; // error, so assume unsupported
  90. });
  91. }
  92. function _checkBlobSupport(idb) {
  93. if (typeof supportsBlobs === 'boolean') {
  94. return _promise2.default.resolve(supportsBlobs);
  95. }
  96. return _checkBlobSupportWithoutCaching(idb).then(function (value) {
  97. supportsBlobs = value;
  98. return supportsBlobs;
  99. });
  100. }
  101. function _deferReadiness(dbInfo) {
  102. var dbContext = dbContexts[dbInfo.name];
  103. // Create a deferred object representing the current database operation.
  104. var deferredOperation = {};
  105. deferredOperation.promise = new _promise2.default(function (resolve, reject) {
  106. deferredOperation.resolve = resolve;
  107. deferredOperation.reject = reject;
  108. });
  109. // Enqueue the deferred operation.
  110. dbContext.deferredOperations.push(deferredOperation);
  111. // Chain its promise to the database readiness.
  112. if (!dbContext.dbReady) {
  113. dbContext.dbReady = deferredOperation.promise;
  114. } else {
  115. dbContext.dbReady = dbContext.dbReady.then(function () {
  116. return deferredOperation.promise;
  117. });
  118. }
  119. }
  120. function _advanceReadiness(dbInfo) {
  121. var dbContext = dbContexts[dbInfo.name];
  122. // Dequeue a deferred operation.
  123. var deferredOperation = dbContext.deferredOperations.pop();
  124. // Resolve its promise (which is part of the database readiness
  125. // chain of promises).
  126. if (deferredOperation) {
  127. deferredOperation.resolve();
  128. return deferredOperation.promise;
  129. }
  130. }
  131. function _rejectReadiness(dbInfo, err) {
  132. var dbContext = dbContexts[dbInfo.name];
  133. // Dequeue a deferred operation.
  134. var deferredOperation = dbContext.deferredOperations.pop();
  135. // Reject its promise (which is part of the database readiness
  136. // chain of promises).
  137. if (deferredOperation) {
  138. deferredOperation.reject(err);
  139. return deferredOperation.promise;
  140. }
  141. }
  142. function _getConnection(dbInfo, upgradeNeeded) {
  143. return new _promise2.default(function (resolve, reject) {
  144. dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
  145. if (dbInfo.db) {
  146. if (upgradeNeeded) {
  147. _deferReadiness(dbInfo);
  148. dbInfo.db.close();
  149. } else {
  150. return resolve(dbInfo.db);
  151. }
  152. }
  153. var dbArgs = [dbInfo.name];
  154. if (upgradeNeeded) {
  155. dbArgs.push(dbInfo.version);
  156. }
  157. var openreq = _idb2.default.open.apply(_idb2.default, dbArgs);
  158. if (upgradeNeeded) {
  159. openreq.onupgradeneeded = function (e) {
  160. var db = openreq.result;
  161. try {
  162. db.createObjectStore(dbInfo.storeName);
  163. if (e.oldVersion <= 1) {
  164. // Added when support for blob shims was added
  165. db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
  166. }
  167. } catch (ex) {
  168. if (ex.name === 'ConstraintError') {
  169. console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
  170. } else {
  171. throw ex;
  172. }
  173. }
  174. };
  175. }
  176. openreq.onerror = function (e) {
  177. e.preventDefault();
  178. reject(openreq.error);
  179. };
  180. openreq.onsuccess = function () {
  181. var db = openreq.result;
  182. db.onversionchange = function (e) {
  183. // Triggered when the database is modified (e.g. adding an objectStore) or
  184. // deleted (even when initiated by other sessions in different tabs).
  185. // Closing the connection here prevents those operations from being blocked.
  186. // If the database is accessed again later by this instance, the connection
  187. // will be reopened or the database recreated as needed.
  188. e.target.close();
  189. };
  190. resolve(db);
  191. _advanceReadiness(dbInfo);
  192. };
  193. });
  194. }
  195. function _getOriginalConnection(dbInfo) {
  196. return _getConnection(dbInfo, false);
  197. }
  198. function _getUpgradedConnection(dbInfo) {
  199. return _getConnection(dbInfo, true);
  200. }
  201. function _isUpgradeNeeded(dbInfo, defaultVersion) {
  202. if (!dbInfo.db) {
  203. return true;
  204. }
  205. var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
  206. var isDowngrade = dbInfo.version < dbInfo.db.version;
  207. var isUpgrade = dbInfo.version > dbInfo.db.version;
  208. if (isDowngrade) {
  209. // If the version is not the default one
  210. // then warn for impossible downgrade.
  211. if (dbInfo.version !== defaultVersion) {
  212. console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
  213. }
  214. // Align the versions to prevent errors.
  215. dbInfo.version = dbInfo.db.version;
  216. }
  217. if (isUpgrade || isNewStore) {
  218. // If the store is new then increment the version (if needed).
  219. // This will trigger an "upgradeneeded" event which is required
  220. // for creating a store.
  221. if (isNewStore) {
  222. var incVersion = dbInfo.db.version + 1;
  223. if (incVersion > dbInfo.version) {
  224. dbInfo.version = incVersion;
  225. }
  226. }
  227. return true;
  228. }
  229. return false;
  230. }
  231. // encode a blob for indexeddb engines that don't support blobs
  232. function _encodeBlob(blob) {
  233. return new _promise2.default(function (resolve, reject) {
  234. var reader = new FileReader();
  235. reader.onerror = reject;
  236. reader.onloadend = function (e) {
  237. var base64 = btoa(e.target.result || '');
  238. resolve({
  239. __local_forage_encoded_blob: true,
  240. data: base64,
  241. type: blob.type
  242. });
  243. };
  244. reader.readAsBinaryString(blob);
  245. });
  246. }
  247. // decode an encoded blob
  248. function _decodeBlob(encodedBlob) {
  249. var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
  250. return (0, _createBlob2.default)([arrayBuff], { type: encodedBlob.type });
  251. }
  252. // is this one of our fancy encoded blobs?
  253. function _isEncodedBlob(value) {
  254. return value && value.__local_forage_encoded_blob;
  255. }
  256. // Specialize the default `ready()` function by making it dependent
  257. // on the current database operations. Thus, the driver will be actually
  258. // ready when it's been initialized (default) *and* there are no pending
  259. // operations on the database (initiated by some other instances).
  260. function _fullyReady(callback) {
  261. var self = this;
  262. var promise = self._initReady().then(function () {
  263. var dbContext = dbContexts[self._dbInfo.name];
  264. if (dbContext && dbContext.dbReady) {
  265. return dbContext.dbReady;
  266. }
  267. });
  268. (0, _executeTwoCallbacks2.default)(promise, callback, callback);
  269. return promise;
  270. }
  271. // Try to establish a new db connection to replace the
  272. // current one which is broken (i.e. experiencing
  273. // InvalidStateError while creating a transaction).
  274. function _tryReconnect(dbInfo) {
  275. _deferReadiness(dbInfo);
  276. var dbContext = dbContexts[dbInfo.name];
  277. var forages = dbContext.forages;
  278. for (var i = 0; i < forages.length; i++) {
  279. var forage = forages[i];
  280. if (forage._dbInfo.db) {
  281. forage._dbInfo.db.close();
  282. forage._dbInfo.db = null;
  283. }
  284. }
  285. dbInfo.db = null;
  286. return _getOriginalConnection(dbInfo).then(function (db) {
  287. dbInfo.db = db;
  288. if (_isUpgradeNeeded(dbInfo)) {
  289. // Reopen the database for upgrading.
  290. return _getUpgradedConnection(dbInfo);
  291. }
  292. return db;
  293. }).then(function (db) {
  294. // store the latest db reference
  295. // in case the db was upgraded
  296. dbInfo.db = dbContext.db = db;
  297. for (var i = 0; i < forages.length; i++) {
  298. forages[i]._dbInfo.db = db;
  299. }
  300. }).catch(function (err) {
  301. _rejectReadiness(dbInfo, err);
  302. throw err;
  303. });
  304. }
  305. // FF doesn't like Promises (micro-tasks) and IDDB store operations,
  306. // so we have to do it with callbacks
  307. function createTransaction(dbInfo, mode, callback, retries) {
  308. if (retries === undefined) {
  309. retries = 1;
  310. }
  311. try {
  312. var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
  313. callback(null, tx);
  314. } catch (err) {
  315. if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
  316. return _promise2.default.resolve().then(function () {
  317. if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
  318. // increase the db version, to create the new ObjectStore
  319. if (dbInfo.db) {
  320. dbInfo.version = dbInfo.db.version + 1;
  321. }
  322. // Reopen the database for upgrading.
  323. return _getUpgradedConnection(dbInfo);
  324. }
  325. }).then(function () {
  326. return _tryReconnect(dbInfo).then(function () {
  327. createTransaction(dbInfo, mode, callback, retries - 1);
  328. });
  329. }).catch(callback);
  330. }
  331. callback(err);
  332. }
  333. }
  334. function createDbContext() {
  335. return {
  336. // Running localForages sharing a database.
  337. forages: [],
  338. // Shared database.
  339. db: null,
  340. // Database readiness (promise).
  341. dbReady: null,
  342. // Deferred operations on the database.
  343. deferredOperations: []
  344. };
  345. }
  346. // Open the IndexedDB database (automatically creates one if one didn't
  347. // previously exist), using any options set in the config.
  348. function _initStorage(options) {
  349. var self = this;
  350. var dbInfo = {
  351. db: null
  352. };
  353. if (options) {
  354. for (var i in options) {
  355. dbInfo[i] = options[i];
  356. }
  357. }
  358. // Get the current context of the database;
  359. var dbContext = dbContexts[dbInfo.name];
  360. // ...or create a new context.
  361. if (!dbContext) {
  362. dbContext = createDbContext();
  363. // Register the new context in the global container.
  364. dbContexts[dbInfo.name] = dbContext;
  365. }
  366. // Register itself as a running localForage in the current context.
  367. dbContext.forages.push(self);
  368. // Replace the default `ready()` function with the specialized one.
  369. if (!self._initReady) {
  370. self._initReady = self.ready;
  371. self.ready = _fullyReady;
  372. }
  373. // Create an array of initialization states of the related localForages.
  374. var initPromises = [];
  375. function ignoreErrors() {
  376. // Don't handle errors here,
  377. // just makes sure related localForages aren't pending.
  378. return _promise2.default.resolve();
  379. }
  380. for (var j = 0; j < dbContext.forages.length; j++) {
  381. var forage = dbContext.forages[j];
  382. if (forage !== self) {
  383. // Don't wait for itself...
  384. initPromises.push(forage._initReady().catch(ignoreErrors));
  385. }
  386. }
  387. // Take a snapshot of the related localForages.
  388. var forages = dbContext.forages.slice(0);
  389. // Initialize the connection process only when
  390. // all the related localForages aren't pending.
  391. return _promise2.default.all(initPromises).then(function () {
  392. dbInfo.db = dbContext.db;
  393. // Get the connection or open a new one without upgrade.
  394. return _getOriginalConnection(dbInfo);
  395. }).then(function (db) {
  396. dbInfo.db = db;
  397. if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
  398. // Reopen the database for upgrading.
  399. return _getUpgradedConnection(dbInfo);
  400. }
  401. return db;
  402. }).then(function (db) {
  403. dbInfo.db = dbContext.db = db;
  404. self._dbInfo = dbInfo;
  405. // Share the final connection amongst related localForages.
  406. for (var k = 0; k < forages.length; k++) {
  407. var forage = forages[k];
  408. if (forage !== self) {
  409. // Self is already up-to-date.
  410. forage._dbInfo.db = dbInfo.db;
  411. forage._dbInfo.version = dbInfo.version;
  412. }
  413. }
  414. });
  415. }
  416. function getItem(key, callback) {
  417. var self = this;
  418. key = (0, _normalizeKey2.default)(key);
  419. var promise = new _promise2.default(function (resolve, reject) {
  420. self.ready().then(function () {
  421. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  422. if (err) {
  423. return reject(err);
  424. }
  425. try {
  426. var store = transaction.objectStore(self._dbInfo.storeName);
  427. var req = store.get(key);
  428. req.onsuccess = function () {
  429. var value = req.result;
  430. if (value === undefined) {
  431. value = null;
  432. }
  433. if (_isEncodedBlob(value)) {
  434. value = _decodeBlob(value);
  435. }
  436. resolve(value);
  437. };
  438. req.onerror = function () {
  439. reject(req.error);
  440. };
  441. } catch (e) {
  442. reject(e);
  443. }
  444. });
  445. }).catch(reject);
  446. });
  447. (0, _executeCallback2.default)(promise, callback);
  448. return promise;
  449. }
  450. // Iterate over all items stored in database.
  451. function iterate(iterator, callback) {
  452. var self = this;
  453. var promise = new _promise2.default(function (resolve, reject) {
  454. self.ready().then(function () {
  455. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  456. if (err) {
  457. return reject(err);
  458. }
  459. try {
  460. var store = transaction.objectStore(self._dbInfo.storeName);
  461. var req = store.openCursor();
  462. var iterationNumber = 1;
  463. req.onsuccess = function () {
  464. var cursor = req.result;
  465. if (cursor) {
  466. var value = cursor.value;
  467. if (_isEncodedBlob(value)) {
  468. value = _decodeBlob(value);
  469. }
  470. var result = iterator(value, cursor.key, iterationNumber++);
  471. // when the iterator callback returns any
  472. // (non-`undefined`) value, then we stop
  473. // the iteration immediately
  474. if (result !== void 0) {
  475. resolve(result);
  476. } else {
  477. cursor.continue();
  478. }
  479. } else {
  480. resolve();
  481. }
  482. };
  483. req.onerror = function () {
  484. reject(req.error);
  485. };
  486. } catch (e) {
  487. reject(e);
  488. }
  489. });
  490. }).catch(reject);
  491. });
  492. (0, _executeCallback2.default)(promise, callback);
  493. return promise;
  494. }
  495. function setItem(key, value, callback) {
  496. var self = this;
  497. key = (0, _normalizeKey2.default)(key);
  498. var promise = new _promise2.default(function (resolve, reject) {
  499. var dbInfo;
  500. self.ready().then(function () {
  501. dbInfo = self._dbInfo;
  502. if (toString.call(value) === '[object Blob]') {
  503. return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
  504. if (blobSupport) {
  505. return value;
  506. }
  507. return _encodeBlob(value);
  508. });
  509. }
  510. return value;
  511. }).then(function (value) {
  512. createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
  513. if (err) {
  514. return reject(err);
  515. }
  516. try {
  517. var store = transaction.objectStore(self._dbInfo.storeName);
  518. // The reason we don't _save_ null is because IE 10 does
  519. // not support saving the `null` type in IndexedDB. How
  520. // ironic, given the bug below!
  521. // See: https://github.com/mozilla/localForage/issues/161
  522. if (value === null) {
  523. value = undefined;
  524. }
  525. var req = store.put(value, key);
  526. transaction.oncomplete = function () {
  527. // Cast to undefined so the value passed to
  528. // callback/promise is the same as what one would get out
  529. // of `getItem()` later. This leads to some weirdness
  530. // (setItem('foo', undefined) will return `null`), but
  531. // it's not my fault localStorage is our baseline and that
  532. // it's weird.
  533. if (value === undefined) {
  534. value = null;
  535. }
  536. resolve(value);
  537. };
  538. transaction.onabort = transaction.onerror = function () {
  539. var err = req.error ? req.error : req.transaction.error;
  540. reject(err);
  541. };
  542. } catch (e) {
  543. reject(e);
  544. }
  545. });
  546. }).catch(reject);
  547. });
  548. (0, _executeCallback2.default)(promise, callback);
  549. return promise;
  550. }
  551. function removeItem(key, callback) {
  552. var self = this;
  553. key = (0, _normalizeKey2.default)(key);
  554. var promise = new _promise2.default(function (resolve, reject) {
  555. self.ready().then(function () {
  556. createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
  557. if (err) {
  558. return reject(err);
  559. }
  560. try {
  561. var store = transaction.objectStore(self._dbInfo.storeName);
  562. // We use a Grunt task to make this safe for IE and some
  563. // versions of Android (including those used by Cordova).
  564. // Normally IE won't like `.delete()` and will insist on
  565. // using `['delete']()`, but we have a build step that
  566. // fixes this for us now.
  567. var req = store.delete(key);
  568. transaction.oncomplete = function () {
  569. resolve();
  570. };
  571. transaction.onerror = function () {
  572. reject(req.error);
  573. };
  574. // The request will be also be aborted if we've exceeded our storage
  575. // space.
  576. transaction.onabort = function () {
  577. var err = req.error ? req.error : req.transaction.error;
  578. reject(err);
  579. };
  580. } catch (e) {
  581. reject(e);
  582. }
  583. });
  584. }).catch(reject);
  585. });
  586. (0, _executeCallback2.default)(promise, callback);
  587. return promise;
  588. }
  589. function clear(callback) {
  590. var self = this;
  591. var promise = new _promise2.default(function (resolve, reject) {
  592. self.ready().then(function () {
  593. createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
  594. if (err) {
  595. return reject(err);
  596. }
  597. try {
  598. var store = transaction.objectStore(self._dbInfo.storeName);
  599. var req = store.clear();
  600. transaction.oncomplete = function () {
  601. resolve();
  602. };
  603. transaction.onabort = transaction.onerror = function () {
  604. var err = req.error ? req.error : req.transaction.error;
  605. reject(err);
  606. };
  607. } catch (e) {
  608. reject(e);
  609. }
  610. });
  611. }).catch(reject);
  612. });
  613. (0, _executeCallback2.default)(promise, callback);
  614. return promise;
  615. }
  616. function length(callback) {
  617. var self = this;
  618. var promise = new _promise2.default(function (resolve, reject) {
  619. self.ready().then(function () {
  620. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  621. if (err) {
  622. return reject(err);
  623. }
  624. try {
  625. var store = transaction.objectStore(self._dbInfo.storeName);
  626. var req = store.count();
  627. req.onsuccess = function () {
  628. resolve(req.result);
  629. };
  630. req.onerror = function () {
  631. reject(req.error);
  632. };
  633. } catch (e) {
  634. reject(e);
  635. }
  636. });
  637. }).catch(reject);
  638. });
  639. (0, _executeCallback2.default)(promise, callback);
  640. return promise;
  641. }
  642. function key(n, callback) {
  643. var self = this;
  644. var promise = new _promise2.default(function (resolve, reject) {
  645. if (n < 0) {
  646. resolve(null);
  647. return;
  648. }
  649. self.ready().then(function () {
  650. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  651. if (err) {
  652. return reject(err);
  653. }
  654. try {
  655. var store = transaction.objectStore(self._dbInfo.storeName);
  656. var advanced = false;
  657. var req = store.openKeyCursor();
  658. req.onsuccess = function () {
  659. var cursor = req.result;
  660. if (!cursor) {
  661. // this means there weren't enough keys
  662. resolve(null);
  663. return;
  664. }
  665. if (n === 0) {
  666. // We have the first key, return it if that's what they
  667. // wanted.
  668. resolve(cursor.key);
  669. } else {
  670. if (!advanced) {
  671. // Otherwise, ask the cursor to skip ahead n
  672. // records.
  673. advanced = true;
  674. cursor.advance(n);
  675. } else {
  676. // When we get here, we've got the nth key.
  677. resolve(cursor.key);
  678. }
  679. }
  680. };
  681. req.onerror = function () {
  682. reject(req.error);
  683. };
  684. } catch (e) {
  685. reject(e);
  686. }
  687. });
  688. }).catch(reject);
  689. });
  690. (0, _executeCallback2.default)(promise, callback);
  691. return promise;
  692. }
  693. function keys(callback) {
  694. var self = this;
  695. var promise = new _promise2.default(function (resolve, reject) {
  696. self.ready().then(function () {
  697. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  698. if (err) {
  699. return reject(err);
  700. }
  701. try {
  702. var store = transaction.objectStore(self._dbInfo.storeName);
  703. var req = store.openKeyCursor();
  704. var keys = [];
  705. req.onsuccess = function () {
  706. var cursor = req.result;
  707. if (!cursor) {
  708. resolve(keys);
  709. return;
  710. }
  711. keys.push(cursor.key);
  712. cursor.continue();
  713. };
  714. req.onerror = function () {
  715. reject(req.error);
  716. };
  717. } catch (e) {
  718. reject(e);
  719. }
  720. });
  721. }).catch(reject);
  722. });
  723. (0, _executeCallback2.default)(promise, callback);
  724. return promise;
  725. }
  726. function dropInstance(options, callback) {
  727. callback = _getCallback2.default.apply(this, arguments);
  728. var currentConfig = this.config();
  729. options = typeof options !== 'function' && options || {};
  730. if (!options.name) {
  731. options.name = options.name || currentConfig.name;
  732. options.storeName = options.storeName || currentConfig.storeName;
  733. }
  734. var self = this;
  735. var promise;
  736. if (!options.name) {
  737. promise = _promise2.default.reject('Invalid arguments');
  738. } else {
  739. var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
  740. var dbPromise = isCurrentDb ? _promise2.default.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
  741. var dbContext = dbContexts[options.name];
  742. var forages = dbContext.forages;
  743. dbContext.db = db;
  744. for (var i = 0; i < forages.length; i++) {
  745. forages[i]._dbInfo.db = db;
  746. }
  747. return db;
  748. });
  749. if (!options.storeName) {
  750. promise = dbPromise.then(function (db) {
  751. _deferReadiness(options);
  752. var dbContext = dbContexts[options.name];
  753. var forages = dbContext.forages;
  754. db.close();
  755. for (var i = 0; i < forages.length; i++) {
  756. var forage = forages[i];
  757. forage._dbInfo.db = null;
  758. }
  759. var dropDBPromise = new _promise2.default(function (resolve, reject) {
  760. var req = _idb2.default.deleteDatabase(options.name);
  761. req.onerror = function () {
  762. var db = req.result;
  763. if (db) {
  764. db.close();
  765. }
  766. reject(req.error);
  767. };
  768. req.onblocked = function () {
  769. // Closing all open connections in onversionchange handler should prevent this situation, but if
  770. // we do get here, it just means the request remains pending - eventually it will succeed or error
  771. console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed');
  772. };
  773. req.onsuccess = function () {
  774. var db = req.result;
  775. if (db) {
  776. db.close();
  777. }
  778. resolve(db);
  779. };
  780. });
  781. return dropDBPromise.then(function (db) {
  782. dbContext.db = db;
  783. for (var i = 0; i < forages.length; i++) {
  784. var _forage = forages[i];
  785. _advanceReadiness(_forage._dbInfo);
  786. }
  787. }).catch(function (err) {
  788. (_rejectReadiness(options, err) || _promise2.default.resolve()).catch(function () {});
  789. throw err;
  790. });
  791. });
  792. } else {
  793. promise = dbPromise.then(function (db) {
  794. if (!db.objectStoreNames.contains(options.storeName)) {
  795. return;
  796. }
  797. var newVersion = db.version + 1;
  798. _deferReadiness(options);
  799. var dbContext = dbContexts[options.name];
  800. var forages = dbContext.forages;
  801. db.close();
  802. for (var i = 0; i < forages.length; i++) {
  803. var forage = forages[i];
  804. forage._dbInfo.db = null;
  805. forage._dbInfo.version = newVersion;
  806. }
  807. var dropObjectPromise = new _promise2.default(function (resolve, reject) {
  808. var req = _idb2.default.open(options.name, newVersion);
  809. req.onerror = function (err) {
  810. var db = req.result;
  811. db.close();
  812. reject(err);
  813. };
  814. req.onupgradeneeded = function () {
  815. var db = req.result;
  816. db.deleteObjectStore(options.storeName);
  817. };
  818. req.onsuccess = function () {
  819. var db = req.result;
  820. db.close();
  821. resolve(db);
  822. };
  823. });
  824. return dropObjectPromise.then(function (db) {
  825. dbContext.db = db;
  826. for (var j = 0; j < forages.length; j++) {
  827. var _forage2 = forages[j];
  828. _forage2._dbInfo.db = db;
  829. _advanceReadiness(_forage2._dbInfo);
  830. }
  831. }).catch(function (err) {
  832. (_rejectReadiness(options, err) || _promise2.default.resolve()).catch(function () {});
  833. throw err;
  834. });
  835. });
  836. }
  837. }
  838. (0, _executeCallback2.default)(promise, callback);
  839. return promise;
  840. }
  841. var asyncStorage = {
  842. _driver: 'asyncStorage',
  843. _initStorage: _initStorage,
  844. _support: (0, _isIndexedDBValid2.default)(),
  845. iterate: iterate,
  846. getItem: getItem,
  847. setItem: setItem,
  848. removeItem: removeItem,
  849. clear: clear,
  850. length: length,
  851. key: key,
  852. keys: keys,
  853. dropInstance: dropInstance
  854. };
  855. exports.default = asyncStorage;
  856. module.exports = exports['default'];
  857. });