Skip to content

Instantly share code, notes, and snippets.

@phoboslab
Created January 19, 2015 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phoboslab/0386df6db79386b9c5cc to your computer and use it in GitHub Desktop.
Save phoboslab/0386df6db79386b9c5cc to your computer and use it in GitHub Desktop.
// idbsimple - tiny wrapper around indexeDB to behave like an
// asynchronous localStorage.
// API (all callbacks are optional):
// idbsimple.getItem(key, function(error, value){...});
// idbsimple.setItem(key, value, function(error){...});
// idbsimple.removeItem(key, function(error){...});
// idbsimple.clear(function(error){...});
// idbsimple.delete();
(function(window){
var _STATUS = { NOT_OPEN: 1, OPENING: 2, OPEN: 4, FAILED: 8 },
databaseName = 'SimpleIDB',
storeName = 'values',
db = null,
queue = [],
indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB,
status = indexedDB ? _STATUS.NOT_OPEN : _STATUS.FAILED;
var execQueue = function() {
for( var i = 0; i < queue.length; i++ ) {
queue[i]();
}
queue = [];
};
var exec = function(mode, action, callback, params) {
if( status === _STATUS.OPEN ) {
var store = db.transaction(storeName, mode).objectStore(storeName);
var req = store[action].apply(store, params);
if( callback ) {
req.onsuccess = function(){
callback(null, req.result);
};
req.onerror = function(){
callback(req.error, null);
};
}
}
else if( status === _STATUS.NOT_OPEN || status === _STATUS.OPENING ) {
queue.push( exec.bind(this, mode, action, callback, params) );
if( status === _STATUS.NOT_OPEN ) {
var req = indexedDB.open(databaseName);
req.onupgradeneeded = function() {
req.result.createObjectStore(storeName);
};
req.onsuccess = function() {
status = _STATUS.OPEN;
db = req.result;
execQueue();
};
req.onerror = function() {
status = _STATUS.FAILED;
execQueue();
};
}
}
else if( this.status === _STATUS.FAILED && callback ) {
callback(status);
}
};
window.idbsimple = {
'getItem': function(key, callback) {
exec('readonly', 'get', callback, [key]);
},
'setItem': function(key, value, callback) {
exec('readwrite', 'put', callback, [value, key]);
},
'removeItem': function(key, callback) {
exec('readwrite', 'delete', callback, [key]);
},
'clear': function(callback) {
exec('readwrite', 'clear', callback, []);
},
'delete': function() {
if( indexedDB ) {
status = _STATUS.NOT_OPEN;
indexedDB.deleteDatabase(databaseName);
}
}
};
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment