Instantly share code, notes, and snippets.

Embed
What would you like to do?
function getCache(name) {
return new Promise((resolve, reject) => {
const version = 1;
const request = indexedDB.open(name, version);
request.onsuccess = event => {
const db = event.target.result;
/*
* Returns a Promise that resolves with an object
* which contains { put, get } helpers.
*/
resolve({
put: (key, value) =>
new Promise((resolve, reject) => {
try {
const result = db
.transaction([name], "readwrite")
.objectStore(name)
.put(value, key);
result.onsuccess = resolve;
result.onerror = reject;
} catch (e) {
reject(e);
}
}),
/*
* Returns a Promise that resolves with the `value` for `key`.
*/
get: key =>
new Promise((resolve, reject) => {
try {
const result = db
.transaction([name])
.objectStore(name)
.get(key);
result.onsuccess = event => {
resolve(event.target.result);
};
result.onerror = reject;
} catch (e) {
reject(e);
}
})
});
};
// This will open/create the database.
request.onupgradeneeded = event => {
const db = event.target.result;
db.createObjectStore(name);
};
request.onerror = reject;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment