I've created a caching service using OOP techniques combined with the revealing module pattern and the angular-cache library. New CacheDataClass
objects are instantiated using the Factory pattern with RequestFactory
. It has generic methods for get, set and reset data. It can be extended to override those methods. I would be very grateful if this can be reviewed and for any suggestions for improvement.
The factory itself:
(function() {
'use strict';
angular
.module('dataservices')
.factory('CacheDataClass', CacheDataClass);
CacheDataClass.$inject = ['CacheFactory'];
function CacheDataClass(CacheFactory) {
var CacheData = function(uid) {
this.uid = uid;
this.newData = null;
this.cache = this.initCache();
};
CacheData.prototype = {
constructor: CacheData,
initCache: function() {
var self = this;
if (!CacheFactory.get(self.uid + '/cache')) {
CacheFactory.createCache(self.uid + '/cache', {
maxAge: 24 * 60 * 60 * 1000,
deleteOnExpire: 'aggressive'
});
}
var cache = CacheFactory.get(self.uid + '/cache');
self.cache = cache;
return cache;
},
getData: function() {
var self = this;
self.newData = self.cache.get(self.uid) ?
self.cache.get(self.uid) :
{};
return self.newData;
},
setData: function(data) {
var self = this;
var cache = self.initCache();
cache.put(self.uid, data);
self.cache = cache;
},
resetData: function() {
var self = this;
self.cache.remove(self.uid);
self.newData = {};
return self.newData;
}
};
return CacheData;
}
})();
Request factory:
(function() {
'use strict';
angular
.module('dataservices')
.factory('RequestFactory', RequestFactory);
RequestFactory.$inject = ['CacheDataClass'];
function RequestFactory(CacheDataClass) {
return {
createCache: function(uid) {
return new CacheDataClass(uid);
}
};
}
})();
Example implementation:
(function() {
'use strict';
angular
.module('cacheExample')
.controller('CacheExampleController', CacheExampleController);
CacheExampleController.$inject = ['CacheFactory', 'RequestFactory', '$stateParams'];
function CacheExampleController(CacheFactory, RequestFactory, $stateParams) {
var vm = this;
activate();
function activate() {
vm.paramsCache = RequestFactory.createCache($location.path() + userID);
}
function setCache() {
vm.paramsCache.setData({
userID: $stateParams.userID,
email: $stateParams.email,
});
}
}
})();