Created
May 2, 2013 15:08
-
-
Save lrvick/5502865 to your computer and use it in GitHub Desktop.
Angular socket data caching/retrieval pattern check service for cached data
else check local storage for data (optional)
else make socket request for data (optional)
then create listener for data from socket
save obtained data to service
save obtained data to localStorage (optional)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ## Fetch Data | |
* | |
* @param {String} key Data source to request | |
* @param {Boolean} use_storage set/get from localStorage | |
* @param {Object} request JSON formatted request for server | |
* | |
* @return {Object} a $q.defer().promise for the data requested | |
* | |
*/ | |
service.fetch = | |
function(key, use_storage, request){ | |
var defer = $q.defer() | |
var use_storage = use_storage || true | |
var data = this[key] ? this[key] : false | |
if (!data && use_storage) data = storageService.get(key) | |
if (data){ | |
defer.resolve(data) | |
} else { | |
if (request){ | |
$rootScope.$watch | |
( socketService.open | |
, function(newValue,oldValue){ | |
if (newValue == true){ | |
socketService.send(request) | |
} | |
} | |
) | |
} | |
$rootScope.$on | |
( enumsService.socket + key | |
, function(event, data){ | |
this[key] = data | |
if (use_storage) storageService.set('key',data) | |
defer.resolve(data) | |
} | |
) | |
$timeout | |
( defer.resolve | |
( { status:enumsService.dataStatus.failure | |
, message: 'server timeout' | |
} | |
) | |
, 5000 | |
) | |
} | |
return defer.promise | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment