Skip to content

Instantly share code, notes, and snippets.

@danb-humaan
Last active March 21, 2016 08:49
Show Gist options
  • Save danb-humaan/05c68e9fba47534a6d51 to your computer and use it in GitHub Desktop.
Save danb-humaan/05c68e9fba47534a6d51 to your computer and use it in GitHub Desktop.
/**
* Fetches the value associated with key from localStorage. If the key/value aren't in localStorage, you can optional provide a callback to run as a fallback getter.
* The callback will also be run if the localStorage cache has expired. You can use {@link LocalStorage#setItem} in the callback to save the results from the callback back to localStorage.
*
* @example <caption>Fetch from localStorage with no callback and get the response returned.</caption>
* var response = LocalStorage.getItem('key');
*
* @example <caption>Fetch from localStorage and handle response in a callback.</caption>
* LocalStorage.getItem('key', function(response) {
* if (response === null) {
* // Nothing in localStorage.
* } else {
* // Got data back from localStorage.
* }
* });
*
* @kind function
* @function LocalStorage#getItem
*
* @param {!string} key - Name of the key in localStorage.
* @param {?function} [optionalCallback=null] - If you want to handle the response in a callback, provide a callback and check the response.
* @returns {*} Returns null if localStorage isn't supported, or the key/value isn't in localStorage, returns anything if it was in localStorage, or returns a callback if key/value was empty in localStorage and callback was provided.
*/
getItem: function (key, optionalCallback) {
if (!this.supportsLocalStorage()) {
return null;
}
var callback = function (data) {
data = typeof data !== 'undefined' ? data : null;
return typeof optionalCallback === 'function' ? optionalCallback(data) : data;
};
var value = localStorage.getItem(key);
if (value !== null) {
value = JSON.parse(value);
if (value.hasOwnProperty('__expiry')) {
var expiry = value.__expiry;
var now = Date.now();
if (now >= expiry) {
this.removeItem(key);
return callback();
} else {
// Return the data object only.
return callback(value.__data);
}
} else {
// Value doesn't have expiry data, just send it wholesale.
return callback(value);
}
} else {
return callback();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment