Skip to content

Instantly share code, notes, and snippets.

@melloc01
Created January 22, 2016 19:45
Show Gist options
  • Save melloc01/c72535efe50cab349fd3 to your computer and use it in GitHub Desktop.
Save melloc01/c72535efe50cab349fd3 to your computer and use it in GitHub Desktop.
BaseResource
'use strict';
function BaseResource(uri, $resource, AppSettings, defaultParams, methods) {
var methods = methods || {};
var url = AppSettings.apiUrl + uri + '/:id';
mergeObjects(methods, {
'update': { method:'PUT' },
'where' : { method:'GET', isArray: true }
});
var factory = $resource(url, defaultParams, methods);
factory.cached = false;
factory.cachedParams = {};
factory.all = function (uri, params, cb) {
if (factory.cached && (JSON.stringify(params) == JSON.stringify(factory.cachedParams))) {
typeof(cb) == 'function' && cb(factory.cached);
return factory.cached;
} else {
return this.query(params, {}, function (products) {
factory.cached = products;
factory.cachedParams = params;
typeof(cb) == 'function' && cb(products);
return this;
});
}
};
factory.findOne = function (params, cb) {
return this.query(params, {}, function (entities) {
var entity = entities[0];
cb(entity);
return this;
});
}
return factory;
}
function mergeObjects (destination,source) {
for (var property in source)
destination[property] = source[property];
return destination;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment