Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
/*
* PLEASE NOTE: This function makes use of ES6 promises. Make sure you use the appropriate shim or swap this out for the jQuery equivilant if you need this to run of web browsers that do not support this functionality
* https://github.com/stefanpenner/es6-promise
*
* PARAMS
* @key - Local Storage Cache Key
* @url The URL of the REST endpoint
* @alwaysFresh - Boolean representing when to fetch the data when the cache is stale (out of date). When set to true, the result set will be fetched from the endpoint immediately
*
* Get data back from cache or request from the server when the cache is stale:
* MyCompany.StorageCache.GetLocalStorageItemCacheForKey ( 'ProfileProperties', '/_api/SP.UserProfiles.PeopleManager/GetMyProperties' ).then(function ( results ) {
* //Ensure that there is no error, before processing the results:
* if (typeof results.error !== "undefined") {
* //Process the error (probably an issue with fetching the data)
* return;
* }
* //do stuff with the returned data
* });
*/
(function (storage, $) {
storage.enabled = true;
var constants = {
Requests: {
DataType: 'json',
ContentType: 'application/json;odata=verbose',
Header: { "accept": "application/json;odata=verbose" },
Method: 'GET'
},
Cache: {
//amount of hours the cache lives for (added to the current date when the cache is set)
Offset: 24
},
Errors: {
Ajax: 'Could not retrieve data from server for the storage cache: ',
Storage: 'Your web browser does not support storing settings locally. We will now rely on your browser cache.'
}
};
var getCacheLifeSpanOffset = function () {
var d = new Date();
return d.addHours(constants.Cache.Offset);
};
// Fetch data if not stale
var fetch = function (key) {
var cache = localStorage.getItem(key);
var data = JSON.parse(cache);
if (data && data.payload) {
var stale = false;
if (Date.parse(data.ttl) < Date.now()) {
stale = true;
}
return { 'payload': data.payload, 'stale': stale };
}
};
// Store data
var store = function (key, payload, ttl) {
var data = { timestamp: Date.now(), ttl: ttl, payload: payload };
localStorage.setItem(key, JSON.stringify(data));
};
storage.GetLocalStorageItemCacheForKey = function (key, url, alwaysFresh) {
//Remember to shim the es6 promise functionality or swap out for the jQuery equivilant
return new Promise(function (resolve, reject) {
var cache = storage.enabled ? fetch(key) : false;
if (cache) {
//if we want to always return the cache even if it's stale or if the cache is not stale
if (!alwaysFresh && cache.stale || !cache.stale) {
resolve(cache.payload);
//leave the function if the cache is valid
if (!cache.stale) {
return;
}
}
}
//we always want to ensure fresh results, so go fetch the latest
$.ajax({
dataType: constants.Requests.DataType,
contentType: constants.Requests.ContentType,
headers: constants.Requests.Header,
url: url,
type: constants.Requests.Method,
success: function (response) {
if (storage.enabled) {
store(key, response, getCacheLifeSpanOffset());
}
if (alwaysFresh || !cache) {
resolve(response);
}
},
fail: function (error) {
if (alwaysFresh || !cache) {
reject({ 'error': constants.Errors.Ajax + error });
}
}
});
});
};
function init() {
if (typeof localStorage === 'object') {
try {
localStorage.setItem('localStorage', 1);
localStorage.removeItem('localStorage');
} catch (error) {
Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function setItem() { };
console.log(constants.Errors.Storage);
storage.enabled = false;
}
}
};
init();
})(MyCompany.StorageCache = MyCompany.StorageCache || {}, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment