Skip to content

Instantly share code, notes, and snippets.

@miguel-leon
Last active December 13, 2016 15:53
Show Gist options
  • Save miguel-leon/6b5a74d68286740eb4a9fd63d25f4cc3 to your computer and use it in GitHub Desktop.
Save miguel-leon/6b5a74d68286740eb4a9fd63d25f4cc3 to your computer and use it in GitHub Desktop.
Storage utils for local storage
angular.module('storage.utils', [])
.factory('StorageUnit', ['$localStorage', function ($localStorage) {
function StorageUnit(storageKey) {
this.storageKey = storageKey;
this.content = $localStorage[storageKey];
}
StorageUnit.prototype.get = function () {
return this.content;
};
StorageUnit.prototype.set = function (data) {
return $localStorage[this.storageKey] = this.content = data;
};
return StorageUnit;
}])
.factory('RetrievableStoredData', ['$http', '$q', 'StorageUnit', function ($http, $q, StorageUnit) {
function RetrievableStoredData(url, storageUnit, httpConfig) {
if (angular.isString(storageUnit)) {
storageUnit = new StorageUnit(storageUnit);
}
var self = this;
this.data = storageUnit.get() || $http.get(url, httpConfig)
.then(function (response) {
self.$response = response;
storageUnit.set(response.data);
return (self.data = response.data);
}, function (error) {
self.$error = error;
return (self.data = $q.reject(null));
});
}
RetrievableStoredData.prototype.then = function (success, error) {
return $q.when(this.data).then(success, error);
};
return RetrievableStoredData;
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment