Skip to content

Instantly share code, notes, and snippets.

@acoyfellow
Forked from MaxboDev/storage.js
Last active February 9, 2019 17:53
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 acoyfellow/8285d24e98cc97f938045c3d5abb9890 to your computer and use it in GitHub Desktop.
Save acoyfellow/8285d24e98cc97f938045c3d5abb9890 to your computer and use it in GitHub Desktop.
Simple localStorage like wrapper around indexeddb
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