Skip to content

Instantly share code, notes, and snippets.

@wilsonpage
Created September 11, 2015 14:25
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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);
};
@bithavoc
Copy link

Thank you. Bower this thing dude...

@hossameldeen
Copy link

Thanks, looks awesome! (but haven't tested).

And to people facing my same problem: localForage may be another solution. (also, haven't tested yet)

@nabilfreeman
Copy link

This is great, I managed to use it to quickly hack together a proof of concept for a proposal here:

react-native-async-storage/async-storage#771

Just a note, I initially thought that delete() was a replacement for removeItem due to key, value in params - it in fact nukes the whole storage object. So be careful 😎

I might write a removeItem, if so will write back here.

@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