Created
January 22, 2016 19:45
-
-
Save melloc01/c72535efe50cab349fd3 to your computer and use it in GitHub Desktop.
BaseResource
This file contains 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
'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