-
-
Save acoyfellow/8285d24e98cc97f938045c3d5abb9890 to your computer and use it in GitHub Desktop.
Simple localStorage like wrapper around indexeddb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Storage(name) { | |
this.name= name; | |
this.ready = (done)=> { | |
var request = window.indexedDB.open(name); | |
request.onupgradeneeded = e => { | |
this.db = e.target.result; | |
this.db.createObjectStore(name); | |
}; | |
request.onsuccess = e => { | |
this.db = e.target.result; | |
done(); | |
}; | |
request.onerror = e => { | |
this.db = e.target.result; | |
console.error(e); | |
}; | |
}; | |
}; | |
Storage.prototype.get = function(key, cb) { | |
return this.ready(()=>{ | |
var request = this.getStore().get(key); | |
request.onsuccess = cb ? e=>cb(e.target.result) : console.log; | |
request.onerror = cb ? e=>cb(e.target.result) : console.error; | |
}); | |
}; | |
Storage.prototype.getStore = function() { | |
return this.db | |
.transaction([this.name], 'readwrite') | |
.objectStore(this.name); | |
}; | |
Storage.prototype.set = function(key, value, cb) { | |
return this.ready(()=> { | |
var request = this.getStore().put(value, key); | |
request.onsuccess = cb ? cb : console.log; | |
request.onerror = cb ? cb : console.error; | |
}); | |
}; | |
Storage.prototype.delete = function(key, value) { | |
window.indexedDB.deleteDatabase(location.origin); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment