Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*Usage:
return cacheService({ // Replace the $http() with cacheService
url: serviceBase.serviceBaseUri + '/GetSeriesTeam',
method: 'POST', // Works for POST only currently
methodName: 'GetSeriesTeam', // Optional, but recommended if different services use same post object properties.
data: params
}, 10).then(function(response) { // The 10 specifies time duration to cache this object in memory
return response.data;
})*/
! function() {
'use strict';
angular.module('app.cacheService', [])
.factory('cacheService', ['$q', '$http',
function($q, $http) {
var db = {};
var _paramsToStr = function(obj, methodName) {
var methodName = methodName || '';
var str = '';
for (var key in obj) {
str += methodName + '_' + key + '-' + obj[key] + '_';
};
return str;
};
var _post = function(callParams, cacheDuration) {
var cacheDuration = parseInt(cacheDuration) || 0.5;
var deferred = $q.defer();
var query = _paramsToStr(callParams.data, callParams.methodName);
if ((db[query] && db[query].result) && (new Date() < new Date(db[query].insertedOn.getTime() + (cacheDuration * 60000)))) { // 60000 millisecs makes a minute
setTimeout(function() { // angular doesnt like blazing fast resolves
deferred.resolve(JSON.parse(JSON.stringify(db[query].result)));
}, 100);
} else {
db[query] = {};
$http({
url: callParams.url,
method: callParams.method,
data: callParams.data,
cache: false
}).then(function(response) {
if (response.status == 200) {
db[query].result = JSON.parse(JSON.stringify(response));
db[query].insertedOn = new Date();
}
deferred.resolve(JSON.parse(JSON.stringify(response)));
});
};
return deferred.promise;
};
return _post
}
])
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.