Skip to content

Instantly share code, notes, and snippets.

@miguel-leon
Created February 5, 2017 06:14
Show Gist options
  • Save miguel-leon/093e6d0069f646a994e49b858006cf3f to your computer and use it in GitHub Desktop.
Save miguel-leon/093e6d0069f646a994e49b858006cf3f to your computer and use it in GitHub Desktop.
Generalization of some "roles" for services regarding rest resources to allow reuse of code.
angular.module('services-roles', [])
.factory('HelperRole_CommonResourceGetter', function (params, errorHandler) {
/**
* @constructor
* @param {string} name of the resource
* @param {Resource} Resource
* @param {Function.<Array|boolean>} actionArgsMapper
*/
return function (name, Resource, actionArgsMapper) {
var Name = name.charAt(0).toUpperCase() + name.slice(1);
var resource = null;
this['get' + Name] = function (onSuccess, force) {
var args = actionArgsMapper(params[name] && params[name]());
if (!args) {
errorHandler.missedResource();
return null;
}
if (force || !resource || !sameRequested(resource, args[0])) {
resource = Resource.get.apply(null, args);
}
resource.$promise.then(onSuccess, errorHandler.missedResource);
return resource;
};
};
function sameRequested(resource, requested) {
angular.forEach(requested, function (value, key) {
if (resource[key] != /* intentional coercion */ value) return false;
});
return true;
}
})
.factory('HelperRole_CachedResource', function () {
/**
* @constructor
* @param {string} action name of the resource action
* @param {string} name name of the Resource factory/part of the name of method being generated following the action name
* @param {Resource} Resource resource factory
*/
return function (action, name, Resource) {
var resource = null;
this[action + name] = function () {
return resource || (resource = Resource[action]());
};
};
})
.factory('cached', function () {
return function (Resource) {
return angular.forEach(Resource, function (action, name) {
var resource = null;
Resource[name] = function () {
return resource || (resource = action.apply(this, arguments));
};
});
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment