Skip to content

Instantly share code, notes, and snippets.

@giuseppeg
Created February 26, 2018 16:50
Show Gist options
  • Save giuseppeg/467de34fd14af7275d70966a66a86926 to your computer and use it in GitHub Desktop.
Save giuseppeg/467de34fd14af7275d70966a66a86926 to your computer and use it in GitHub Desktop.
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;
});
}
@MihaelIsaev
Copy link

MihaelIsaev commented Feb 8, 2021

Seems it doesn't work nowadays, right?

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