Skip to content

Instantly share code, notes, and snippets.

@wilsonpage
Created September 11, 2015 14:25
Show Gist options
  • Save wilsonpage/01d2eb139959c79e0d9a to your computer and use it in GitHub Desktop.
Save wilsonpage/01d2eb139959c79e0d9a 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(['store'], 'readwrite')
.objectStore('store');
};
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);
};
@pwFoo
Copy link

pwFoo commented Aug 6, 2023

Nice! But searching for a indexeddb solution like that with get by (index) property as additional feature 🙈

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment