Created
September 11, 2015 14:25
-
-
Save wilsonpage/01d2eb139959c79e0d9a 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(['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); | |
}; |
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.
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
Thanks, looks awesome! (but haven't tested).
And to people facing my same problem: localForage may be another solution. (also, haven't tested yet)