Skip to content

Instantly share code, notes, and snippets.

@philipgiuliani
Created July 28, 2015 12:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipgiuliani/2cf5abb59d411626f363 to your computer and use it in GitHub Desktop.
Save philipgiuliani/2cf5abb59d411626f363 to your computer and use it in GitHub Desktop.
Cache helper which uses the localStorage. Promise polyfill maybe required!
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