Created
February 26, 2018 16:50
-
-
Save giuseppeg/467de34fd14af7275d70966a66a86926 to your computer and use it in GitHub Desktop.
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 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
Seems it doesn't work nowadays, right?