UNPKG

gaf-mobile

Version:

GAF mobile Web site

87 lines (73 loc) 2.45 kB
/** * A naive [and incomplete] implementation of IDBObjectStore methods wrapped in * Promises. This is to simplify interaction with IndexedDB, such as setting and * getting entries, to keep us sane. The set of methods implemented here is a * subset of the corresponding methods in IDBObjectStore. */ /* global self */ 'use strict'; (function() { function IDBHelper(dbName, version, callback) { var _db; var _getIdb = function() { if (_db) { return Promise.resolve(_db); } return new Promise(function(resolve, reject) { if (!self.indexedDB) { // IndexedDB is not supported return reject('IndexedDB is not supported on your browser.'); } var request = self.indexedDB.open(dbName, version); request.onupgradeneeded = function(event) { var db = event.target.result; callback(db); }; request.onsuccess = function(event) { _db = event.target.result; return resolve(_db); }; request.onerror = function() { return reject('Cannot get IndexedDB named: ' + dbName); }; }); }; return { transaction: function(store, mode, callback) { return _getIdb().then(function(db) { mode = mode || 'readonly'; var txn = db.transaction(store, mode); var request = callback(txn); return new Promise(function(resolve, reject) { request.onsuccess = function() { resolve(request.result); }; request.onerror = function() { reject(request.error); }; }); }); }, get: function(store, key) { return this.transaction(store, 'readonly', function(txn) { return txn.objectStore(store).get(key); }); }, put: function(store, key, value) { return this.transaction(store, 'readwrite', function(txn) { return txn.objectStore(store).put(value, key); }); }, delete: function(store, key) { return this.transaction(store, 'readwrite', function(txn) { return txn.objectStore(store).delete(key); }); }, getAllKeys: function(store) { return this.transaction(store, 'readonly', function(txn) { return txn.objectStore(store).getAllKeys(); }); } }; } self.IDBHelper = IDBHelper; }());