Skip to content

Instantly share code, notes, and snippets.

@cyclopslabs
Last active August 29, 2015 14:12
Show Gist options
  • Save cyclopslabs/4e76e6ec97a745062903 to your computer and use it in GitHub Desktop.
Save cyclopslabs/4e76e6ec97a745062903 to your computer and use it in GitHub Desktop.
Angular Service with basic lightweight caching
(function() {
'use strict';
angular
.module('app.component.nameOfComponent')
.factory('angularServiceWithCaching', angularServiceWithCaching);
/**
* @ngdoc service
* @name app.component.nameOfComponent.services:angularServiceWithCaching
*
* @requires $http
* @requires $q
* @requires $log
* @requires core.login.services:userFactory
* @requires core.tools.constants:apiEndpoint
*
* @description
* #angularServiceWithCaching Service
* This service will only query the server one time per load. It caches the
* results and will serve cached results on future loads. Technically it only caches
* successful responses. If there is a failed response of any type (including the failed response "400: Bad Request"
* that is returned when there just isn't any data) it will not cache that.
* Future calls to the service will continue to get a successful response.
*
* There are two main functions for this service : 1 to get available params for a specific chapter, and another to read the data
* from selected set of params
*
* Note that 'load' as used above means 'Newed Up Instance'.
*
**/
angularServiceWithCaching.$inject = ['$http', '$q', '$log', 'userFactory', 'apiEndpoint'];
function angularServiceWithCaching($http, $q, $log, userFactory, apiEndpoint) {
var maxParams = 20;
var cachedParams = [];
var service = {
getParams: getParams,
clearCachedParams: clearCachedParams,
getMaxParams: getMaxParams,
startLiveReading : startLiveReading,
stopLiveReading : stopLiveReading,
initLiveParams : initLiveParams
};
return service;
/////////////////
/**
* @ngdoc function
* @name app.component.nameOfComponent.services:paramService#getParams
* @methodOf app.component.nameOfComponent.services:paramService
*
* @description
* Returns params from cache if they exist, or uses POST to query for params of a chapter_code.
*
* @param {number} chapter_code The ID of the chapter
* @param {boolean} [ignoreCache=false] Setting ignoreCache to true will ignore any previously cached response.
*
* @return {Promise} (object|error) {data_sets} if success, or an error if rejected.
*
**/
function getParams(chapter_code, ignoreCache) {
var dfd = $q.defer();
if (angular.isNumber(chapter_code)) {
var arraySafeChapterCode = "chapter_" + chapter_code;
// check if we've already cached the params for this chapter:
if (cachedParams[arraySafeChapterCode] && !ignoreCache) {
// return the cached version
dfd.resolve(cachedParams[arraySafeChapterCode]);
} else {
// since we haven't cached this yet, get it from http:
$http.post(apiEndpoint.getParametersUrl, {
session_id: userFactory.getSessionId(),
match: 'chapter:' + chapter_code
})
.success(function(data) {
// add it to the cache for the next time.
cachedParams[arraySafeChapterCode] = data;
// resolve the promise
dfd.resolve(data);
})
.error(function(msg, code) {
dfd.reject(msg);
$log.error(msg, code);
});
}
} else {
dfd.reject();
$log.error('chapter code must be a number, "' + chapter_code + '" was passed');
}
return dfd.promise;
}
/**
* @ngdoc function
* @name app.component.nameOfComponent.services:paramService#clearCachedParams
* @methodOf app.component.nameOfComponent.services:paramService
*
* @description
* Clear Cached Params.
*
*
**/
function clearCachedParams() {
cachedParams = [];
}
/**
* @ngdoc function
* @name app.component.nameOfComponent.services:paramService#getMaxParams
* @methodOf app.component.nameOfComponent.services:paramService
*
* @description
* Returns the number of max params
*
* @return {number} maxParams The maximum number of Parameters able to be added to the selected params list.
*
**/
function getMaxParams() {
return maxParams;
}
/**
* @ngdoc function
* @name app.component.nameOfComponent.services:paramService#startLiveReading
* @methodOf app.component.nameOfComponent.services:paramService
*
* @description
* This method must be called AFTER initLiveParams. It returns data for params specified in the initLiveParams method.
* Intended to be called with a timeout which utilizes the min_delay (returned) to get continually updated data.
*
* @return {promise} Promise with success and min_delay, and an array of param values. Or fail with reason and code.
*
**/
function startLiveReading(params) {
var dfd = $q.defer();
$http.post(apiEndpoint.start, {
session_id: userFactory.getSessionId()
})
.success(function(response){
dfd.resolve(response);
})
.error(function(fail){
dfd.reject(fail);
$log.error('Process Failed to start: ', fail.reason);
});
return dfd.promise;
}
/**
* @ngdoc function
* @name app.component.nameOfComponent.services:paramService#initLiveParams
* @methodOf app.component.nameOfComponent.services:paramService
*
* @description
* Tells the backend to prepare a sample of parameter values. This method will be followed by startLiveReading.
*
* @return {object} Object containing successful initialization of params and the name and units of the params.
*
**/
function initLiveParams() {
var dfd = $q.defer();
$http.post(apiEndpoint.readData, {
session_id: userFactory.getSessionId()
})
.success(function(response){
dfd.resolve(response);
})
.error(function(fail){
dfd.reject(fail);
$log.error('Failed: ' , + fail);
});
return dfd.promise;
}
/**
* @ngdoc function
* @name app.component.nameOfComponent.services:paramService#stopLiveReading
* @methodOf app.component.nameOfComponent.services:paramService
*
* @description
* Tell the backend we want to stop reading live params.
*
* @return {object} Object regarding the success of the backend stopping the live reading of params
*
**/
function stopLiveReading() {
var dfd = $q.defer();
$http.post(apiEndpoint.stop, {
session_id: userFactory.getSessionId()
})
.success(function(response){
dfd.resolve(response);
})
.error(function(fail){
dfd.reject(fail);
$log.error('Failed to stop: ' , + fail);
});
return dfd.promise;
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment