-
-
Save MaxboDev/093f7022a0b597550c53ddbfc199e3bc to your computer and use it in GitHub Desktop.
Simple localStorage like wrapper around indexeddb
This file contains 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.ready = new Promise((resolve, reject) => { | |
var request = window.indexedDB.open(location.origin); | |
request.onupgradeneeded = e => { | |
this.db = e.target.result; | |
this.db.createObjectStore('store'); | |
}; | |
request.onsuccess = e => { | |
this.db = e.target.result; | |
resolve(); | |
}; | |
request.onerror = e => { | |
this.db = e.target.result; | |
reject(e); | |
}; | |
}); | |
} | |
Storage.prototype.get = function(key) { | |
return this.ready.then(() => { | |
return new Promise((resolve, reject) => { | |
var request = this.getStore().get(key); | |
request.onsuccess = e => resolve(e.target.result); | |
request.onerror = reject; | |
}); | |
}); | |
}; | |
Storage.prototype.getStore = function() { | |
return this.db | |
.transaction([name], 'readwrite') | |
.objectStore(name); | |
}; | |
Storage.prototype.set = function(key, value) { | |
return this.ready.then(() => { | |
return new Promise((resolve, reject) => { | |
var request = this.getStore().put(value, key); | |
request.onsuccess = resolve; | |
request.onerror = reject; | |
}); | |
}); | |
}; | |
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