Skip to content

Instantly share code, notes, and snippets.

@MaxboDev
Forked from wilsonpage/storage.js
Last active February 9, 2019 13:04
Show Gist options
  • Save MaxboDev/093f7022a0b597550c53ddbfc199e3bc to your computer and use it in GitHub Desktop.
Save MaxboDev/093f7022a0b597550c53ddbfc199e3bc to your computer and use it in GitHub Desktop.
Simple localStorage like wrapper around indexeddb
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