Created
July 28, 2015 12:22
-
-
Save philipgiuliani/2cf5abb59d411626f363 to your computer and use it in GitHub Desktop.
Cache helper which uses the localStorage. Promise polyfill maybe required!
This file contains hidden or 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
window.Cache = { | |
/** | |
* Fetch a object from the cache, if it does not exist, create it. | |
* | |
* @param {string} key Key to find / store the item in the localStorage. | |
* @param {function} [fetchPromise] Promise to fetch new data | |
* | |
* @example | |
* Cache.fetch("result", (resolve, reject) => { | |
* resolve(5 * 10); | |
* }).then((result) => { | |
* console.log(result); | |
* }); | |
* | |
* @returns {Promise} Returns a promise with the result | |
*/ | |
fetch: function(key, fetchPromise) { | |
return new Promise((resolve, reject) => { | |
// check if it's already chached | |
var cached = localStorage.getItem(key); | |
if (cached) { | |
resolve(JSON.parse(cached)); | |
} | |
// fetch new item | |
else if (fetchPromise) { | |
new Promise(fetchPromise).then((result) => { | |
localStorage.setItem(key, JSON.stringify(result)); | |
resolve(result); | |
}) | |
.catch((error) => reject(error)); | |
} | |
// reject with not found | |
else { | |
reject("KEY NOT FOUND"); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment