diff --git a/dist/restangular.js b/dist/restangular.js index bff968f9..f014fd39 100644 --- a/dist/restangular.js +++ b/dist/restangular.js @@ -1,9 +1,10 @@ /** * Restful Resources service for AngularJS apps - * @version v1.6.0 - 2016-12-25 * @link https://github.com/mgonto/restangular + * @version v1.6.0 - 2017-01-05 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT - */(function (root, factory) { + */(function(root, factory) { + /* global define, require */ // https://github.com/umdjs/umd/blob/master/templates/returnExports.js if (typeof define === 'function' && define.amd) { define(['lodash', 'angular'], factory); @@ -13,1395 +14,1439 @@ // No global export, Restangular will register itself as Angular.js module factory(root._, root.angular); } -}(this, function (_, angular) { - -var restangular = angular.module('restangular', []); - -restangular.provider('Restangular', function() { - // Configuration - var Configurer = {}; - Configurer.init = function(object, config) { - object.configuration = config; - - /** - * Those are HTTP safe methods for which there is no need to pass any data with the request. - */ - var safeMethods= ['get', 'head', 'options', 'trace', 'getlist']; - config.isSafe = function(operation) { - return _.includes(safeMethods, operation.toLowerCase()); - }; +}(this, function(_, angular) { + + var restangular = angular.module('restangular', []); + + restangular.provider('Restangular', function() { + // Configuration + var Configurer = {}; + Configurer.init = function(object, config) { + object.configuration = config; + + /** + * Those are HTTP safe methods for which there is no need to pass any data with the request. + */ + var safeMethods = ['get', 'head', 'options', 'trace', 'getlist']; + config.isSafe = function(operation) { + return _.includes(safeMethods, operation.toLowerCase()); + }; - var absolutePattern = /^https?:\/\//i; - config.isAbsoluteUrl = function(string) { - return _.isUndefined(config.absoluteUrl) || _.isNull(config.absoluteUrl) ? - string && absolutePattern.test(string) : - config.absoluteUrl; - }; + var absolutePattern = /^https?:\/\//i; + config.isAbsoluteUrl = function(string) { + return _.isUndefined(config.absoluteUrl) || _.isNull(config.absoluteUrl) ? + string && absolutePattern.test(string) : + config.absoluteUrl; + }; - config.absoluteUrl = _.isUndefined(config.absoluteUrl) ? true : config.absoluteUrl; - object.setSelfLinkAbsoluteUrl = function(value) { - config.absoluteUrl = value; - }; - /** - * This is the BaseURL to be used with Restangular - */ - config.baseUrl = _.isUndefined(config.baseUrl) ? '' : config.baseUrl; - object.setBaseUrl = function(newBaseUrl) { - config.baseUrl = /\/$/.test(newBaseUrl) ? - newBaseUrl.substring(0, newBaseUrl.length-1) : - newBaseUrl; - return this; - }; + config.absoluteUrl = _.isUndefined(config.absoluteUrl) ? true : config.absoluteUrl; + object.setSelfLinkAbsoluteUrl = function(value) { + config.absoluteUrl = value; + }; + /** + * This is the BaseURL to be used with Restangular + */ + config.baseUrl = _.isUndefined(config.baseUrl) ? '' : config.baseUrl; + object.setBaseUrl = function(newBaseUrl) { + config.baseUrl = /\/$/.test(newBaseUrl) ? + newBaseUrl.substring(0, newBaseUrl.length - 1) : + newBaseUrl; + return this; + }; - /** - * Sets the extra fields to keep from the parents - */ - config.extraFields = config.extraFields || []; - object.setExtraFields = function(newExtraFields) { - config.extraFields = newExtraFields; - return this; - }; + /** + * Sets the extra fields to keep from the parents + */ + config.extraFields = config.extraFields || []; + object.setExtraFields = function(newExtraFields) { + config.extraFields = newExtraFields; + return this; + }; - /** - * Some default $http parameter to be used in EVERY call - **/ - config.defaultHttpFields = config.defaultHttpFields || {}; - object.setDefaultHttpFields = function(values) { - config.defaultHttpFields = values; - return this; - }; + /** + * Some default $http parameter to be used in EVERY call + **/ + config.defaultHttpFields = config.defaultHttpFields || {}; + object.setDefaultHttpFields = function(values) { + config.defaultHttpFields = values; + return this; + }; - /** - * Always return plain data, no restangularized object - **/ - config.plainByDefault = config.plainByDefault || false; - object.setPlainByDefault = function(value) { - config.plainByDefault = value === true ? true : false; - return this; - }; + /** + * Always return plain data, no restangularized object + **/ + config.plainByDefault = config.plainByDefault || false; + object.setPlainByDefault = function(value) { + config.plainByDefault = value === true ? true : false; + return this; + }; - config.withHttpValues = function(httpLocalConfig, obj) { - return _.defaults(obj, httpLocalConfig, config.defaultHttpFields); - }; + config.withHttpValues = function(httpLocalConfig, obj) { + return _.defaults(obj, httpLocalConfig, config.defaultHttpFields); + }; - config.encodeIds = _.isUndefined(config.encodeIds) ? true : config.encodeIds; - object.setEncodeIds = function(encode) { - config.encodeIds = encode; - }; + config.encodeIds = _.isUndefined(config.encodeIds) ? true : config.encodeIds; + object.setEncodeIds = function(encode) { + config.encodeIds = encode; + }; - config.defaultRequestParams = config.defaultRequestParams || { - get: {}, - post: {}, - put: {}, - remove: {}, - common: {} - }; + config.defaultRequestParams = config.defaultRequestParams || { + get: {}, + post: {}, + put: {}, + remove: {}, + common: {} + }; - object.setDefaultRequestParams = function(param1, param2) { - var methods = [], + object.setDefaultRequestParams = function(param1, param2) { + var methods = [], params = param2 || param1; - if (!_.isUndefined(param2)) { - if (_.isArray(param1)) { - methods = param1; + if (!_.isUndefined(param2)) { + if (_.isArray(param1)) { + methods = param1; + } else { + methods.push(param1); + } } else { - methods.push(param1); + methods.push('common'); } - } else { - methods.push('common'); - } - - _.each(methods, function (method) { - config.defaultRequestParams[method] = params; - }); - return this; - }; - object.requestParams = config.defaultRequestParams; + _.each(methods, function(method) { + config.defaultRequestParams[method] = params; + }); + return this; + }; - config.defaultHeaders = config.defaultHeaders || {}; - object.setDefaultHeaders = function(headers) { - config.defaultHeaders = headers; - object.defaultHeaders = config.defaultHeaders; - return this; - }; + object.requestParams = config.defaultRequestParams; - object.defaultHeaders = config.defaultHeaders; + config.defaultHeaders = config.defaultHeaders || {}; + object.setDefaultHeaders = function(headers) { + config.defaultHeaders = headers; + object.defaultHeaders = config.defaultHeaders; + return this; + }; - /** - * Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override - **/ - config.methodOverriders = config.methodOverriders || []; - object.setMethodOverriders = function(values) { - var overriders = _.extend([], values); - if (config.isOverridenMethod('delete', overriders)) { - overriders.push('remove'); - } - config.methodOverriders = overriders; - return this; - }; + object.defaultHeaders = config.defaultHeaders; - config.jsonp = _.isUndefined(config.jsonp) ? false : config.jsonp; - object.setJsonp = function(active) { - config.jsonp = active; - }; + /** + * Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override + **/ + config.methodOverriders = config.methodOverriders || []; + object.setMethodOverriders = function(values) { + var overriders = _.extend([], values); + if (config.isOverridenMethod('delete', overriders)) { + overriders.push('remove'); + } + config.methodOverriders = overriders; + return this; + }; - config.isOverridenMethod = function(method, values) { - var search = values || config.methodOverriders; - return !_.isUndefined(_.find(search, function(one) { - return one.toLowerCase() === method.toLowerCase(); - })); - }; + config.jsonp = _.isUndefined(config.jsonp) ? false : config.jsonp; + object.setJsonp = function(active) { + config.jsonp = active; + }; - /** - * Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams - **/ - config.urlCreator = config.urlCreator || 'path'; - object.setUrlCreator = function(name) { - if (!_.has(config.urlCreatorFactory, name)) { - throw new Error('URL Path selected isn\'t valid'); - } + config.isOverridenMethod = function(method, values) { + var search = values || config.methodOverriders; + return !_.isUndefined(_.find(search, function(one) { + return one.toLowerCase() === method.toLowerCase(); + })); + }; - config.urlCreator = name; - return this; - }; + /** + * Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams + **/ + config.urlCreator = config.urlCreator || 'path'; + object.setUrlCreator = function(name) { + if (!_.has(config.urlCreatorFactory, name)) { + throw new Error('URL Path selected isn\'t valid'); + } - /** - * You can set the restangular fields here. The 3 required fields for Restangular are: - * - * id: Id of the element - * route: name of the route of this element - * parentResource: the reference to the parent resource - * - * All of this fields except for id, are handled (and created) by Restangular. By default, - * the field values will be id, route and parentResource respectively - */ - config.restangularFields = config.restangularFields || { - id: 'id', - route: 'route', - parentResource: 'parentResource', - restangularCollection: 'restangularCollection', - cannonicalId: '__cannonicalId', - etag: 'restangularEtag', - selfLink: 'href', - get: 'get', - getList: 'getList', - put: 'put', - post: 'post', - remove: 'remove', - head: 'head', - trace: 'trace', - options: 'options', - patch: 'patch', - getRestangularUrl: 'getRestangularUrl', - getRequestedUrl: 'getRequestedUrl', - putElement: 'putElement', - addRestangularMethod: 'addRestangularMethod', - getParentList: 'getParentList', - clone: 'clone', - ids: 'ids', - httpConfig: '_$httpConfig', - reqParams: 'reqParams', - one: 'one', - all: 'all', - several: 'several', - oneUrl: 'oneUrl', - allUrl: 'allUrl', - customPUT: 'customPUT', - customPATCH: 'customPATCH', - customPOST: 'customPOST', - customDELETE: 'customDELETE', - customGET: 'customGET', - customGETLIST: 'customGETLIST', - customOperation: 'customOperation', - doPUT: 'doPUT', - doPATCH: 'doPATCH', - doPOST: 'doPOST', - doDELETE: 'doDELETE', - doGET: 'doGET', - doGETLIST: 'doGETLIST', - fromServer: 'fromServer', - withConfig: 'withConfig', - withHttpConfig: 'withHttpConfig', - singleOne: 'singleOne', - plain: 'plain', - save: 'save', - restangularized: 'restangularized' - }; - object.setRestangularFields = function(resFields) { - config.restangularFields = - _.extend(config.restangularFields, resFields); - return this; - }; + config.urlCreator = name; + return this; + }; - config.isRestangularized = function(obj) { - return !!obj[config.restangularFields.restangularized]; - }; + /** + * You can set the restangular fields here. The 3 required fields for Restangular are: + * + * id: Id of the element + * route: name of the route of this element + * parentResource: the reference to the parent resource + * + * All of this fields except for id, are handled (and created) by Restangular. By default, + * the field values will be id, route and parentResource respectively + */ + config.restangularFields = config.restangularFields || { + id: 'id', + route: 'route', + parentResource: 'parentResource', + restangularCollection: 'restangularCollection', + cannonicalId: '__cannonicalId', + etag: 'restangularEtag', + selfLink: 'href', + get: 'get', + getList: 'getList', + put: 'put', + post: 'post', + remove: 'remove', + head: 'head', + trace: 'trace', + options: 'options', + patch: 'patch', + getRestangularUrl: 'getRestangularUrl', + getRequestedUrl: 'getRequestedUrl', + putElement: 'putElement', + addRestangularMethod: 'addRestangularMethod', + getParentList: 'getParentList', + clone: 'clone', + ids: 'ids', + httpConfig: '_$httpConfig', + reqParams: 'reqParams', + one: 'one', + all: 'all', + several: 'several', + oneUrl: 'oneUrl', + allUrl: 'allUrl', + customPUT: 'customPUT', + customPATCH: 'customPATCH', + customPOST: 'customPOST', + customDELETE: 'customDELETE', + customGET: 'customGET', + customGETLIST: 'customGETLIST', + customOperation: 'customOperation', + doPUT: 'doPUT', + doPATCH: 'doPATCH', + doPOST: 'doPOST', + doDELETE: 'doDELETE', + doGET: 'doGET', + doGETLIST: 'doGETLIST', + fromServer: 'fromServer', + withConfig: 'withConfig', + withHttpConfig: 'withHttpConfig', + singleOne: 'singleOne', + plain: 'plain', + save: 'save', + restangularized: 'restangularized' + }; + object.setRestangularFields = function(resFields) { + config.restangularFields = + _.extend(config.restangularFields, resFields); + return this; + }; - config.setFieldToElem = function(field, elem, value) { - var properties = field.split('.'); - var idValue = elem; - _.each(_.initial(properties), function(prop) { - idValue[prop] = {}; - idValue = idValue[prop]; - }); - idValue[_.last(properties)] = value; - return this; - }; + config.isRestangularized = function(obj) { + return !!obj[config.restangularFields.restangularized]; + }; - config.getFieldFromElem = function(field, elem) { - var properties = field.split('.'); - var idValue = elem; - _.each(properties, function(prop) { - if (idValue) { + config.setFieldToElem = function(field, elem, value) { + var properties = field.split('.'); + var idValue = elem; + _.each(_.initial(properties), function(prop) { + idValue[prop] = {}; idValue = idValue[prop]; - } - }); - return angular.copy(idValue); - }; - - config.setIdToElem = function(elem, id /*, route */) { - config.setFieldToElem(config.restangularFields.id, elem, id); - return this; - }; + }); + idValue[_.last(properties)] = value; + return this; + }; - config.getIdFromElem = function(elem) { - return config.getFieldFromElem(config.restangularFields.id, elem); - }; + config.getFieldFromElem = function(field, elem) { + var properties = field.split('.'); + var idValue = elem; + _.each(properties, function(prop) { + if (idValue) { + idValue = idValue[prop]; + } + }); + return angular.copy(idValue); + }; - config.isValidId = function(elemId) { - return '' !== elemId && !_.isUndefined(elemId) && !_.isNull(elemId); - }; + config.setIdToElem = function(elem, id /*, route */ ) { + config.setFieldToElem(config.restangularFields.id, elem, id); + return this; + }; - config.setUrlToElem = function(elem, url /*, route */) { - config.setFieldToElem(config.restangularFields.selfLink, elem, url); - return this; - }; + config.getIdFromElem = function(elem) { + return config.getFieldFromElem(config.restangularFields.id, elem); + }; - config.getUrlFromElem = function(elem) { - return config.getFieldFromElem(config.restangularFields.selfLink, elem); - }; + config.isValidId = function(elemId) { + return '' !== elemId && !_.isUndefined(elemId) && !_.isNull(elemId); + }; - config.useCannonicalId = _.isUndefined(config.useCannonicalId) ? false : config.useCannonicalId; - object.setUseCannonicalId = function(value) { - config.useCannonicalId = value; - return this; - }; + config.setUrlToElem = function(elem, url /*, route */ ) { + config.setFieldToElem(config.restangularFields.selfLink, elem, url); + return this; + }; - config.getCannonicalIdFromElem = function(elem) { - var cannonicalId = elem[config.restangularFields.cannonicalId]; - var actualId = config.isValidId(cannonicalId) ? cannonicalId : config.getIdFromElem(elem); - return actualId; - }; + config.getUrlFromElem = function(elem) { + return config.getFieldFromElem(config.restangularFields.selfLink, elem); + }; - /** - * Sets the Response parser. This is used in case your response isn't directly the data. - * For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}} - * you can extract this data which is the one that needs wrapping - * - * The ResponseExtractor is a function that receives the response and the method executed. - */ + config.useCannonicalId = _.isUndefined(config.useCannonicalId) ? false : config.useCannonicalId; + object.setUseCannonicalId = function(value) { + config.useCannonicalId = value; + return this; + }; - config.responseInterceptors = config.responseInterceptors || []; + config.getCannonicalIdFromElem = function(elem) { + var cannonicalId = elem[config.restangularFields.cannonicalId]; + var actualId = config.isValidId(cannonicalId) ? cannonicalId : config.getIdFromElem(elem); + return actualId; + }; - config.defaultResponseInterceptor = function(data /*, operation, what, url, response, deferred */) { - return data; - }; + /** + * Sets the Response parser. This is used in case your response isn't directly the data. + * For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}} + * you can extract this data which is the one that needs wrapping + * + * The ResponseExtractor is a function that receives the response and the method executed. + */ - config.responseExtractor = function(data, operation, what, url, response, deferred) { - var interceptors = angular.copy(config.responseInterceptors); - interceptors.push(config.defaultResponseInterceptor); - var theData = data; - _.each(interceptors, function(interceptor) { - theData = interceptor(theData, operation, - what, url, response, deferred); - }); - return theData; - }; + config.responseInterceptors = config.responseInterceptors || []; - object.addResponseInterceptor = function(extractor) { - config.responseInterceptors.push(extractor); - return this; - }; + config.defaultResponseInterceptor = function(data /*, operation, what, url, response, deferred */ ) { + return data; + }; - config.errorInterceptors = config.errorInterceptors || []; - object.addErrorInterceptor = function(interceptor) { - config.errorInterceptors.push(interceptor); - return this; - }; + config.responseExtractor = function(data, operation, what, url, response, deferred) { + var interceptors = angular.copy(config.responseInterceptors); + interceptors.push(config.defaultResponseInterceptor); + var theData = data; + _.each(interceptors, function(interceptor) { + theData = interceptor(theData, operation, + what, url, response, deferred); + }); + return theData; + }; - object.setResponseInterceptor = object.addResponseInterceptor; - object.setResponseExtractor = object.addResponseInterceptor; - object.setErrorInterceptor = object.addErrorInterceptor; + object.addResponseInterceptor = function(extractor) { + config.responseInterceptors.push(extractor); + return this; + }; - /** - * Response interceptor is called just before resolving promises. - */ + config.errorInterceptors = config.errorInterceptors || []; + object.addErrorInterceptor = function(interceptor) { + config.errorInterceptors.push(interceptor); + return this; + }; + object.setResponseInterceptor = object.addResponseInterceptor; + object.setResponseExtractor = object.addResponseInterceptor; + object.setErrorInterceptor = object.addErrorInterceptor; - /** - * Request interceptor is called before sending an object to the server. - */ - config.requestInterceptors = config.requestInterceptors || []; + /** + * Response interceptor is called just before resolving promises. + */ - config.defaultInterceptor = function(element, operation, path, url, headers, params, httpConfig) { - return { - element: element, - headers: headers, - params: params, - httpConfig: httpConfig - }; - }; - config.fullRequestInterceptor = function(element, operation, path, url, headers, params, httpConfig) { - var interceptors = angular.copy(config.requestInterceptors); - var defaultRequest = config.defaultInterceptor(element, operation, path, url, headers, params, httpConfig); - return _.reduce(interceptors, function(request, interceptor) { - return _.extend(request, interceptor(request.element, operation, - path, url, request.headers, request.params, request.httpConfig)); - }, defaultRequest); - }; + /** + * Request interceptor is called before sending an object to the server. + */ + config.requestInterceptors = config.requestInterceptors || []; - object.addRequestInterceptor = function(interceptor) { - config.requestInterceptors.push(function(elem, operation, path, url, headers, params, httpConfig) { + config.defaultInterceptor = function(element, operation, path, url, headers, params, httpConfig) { return { + element: element, headers: headers, params: params, - element: interceptor(elem, operation, path, url), httpConfig: httpConfig }; - }); - return this; - }; + }; - object.setRequestInterceptor = object.addRequestInterceptor; + config.fullRequestInterceptor = function(element, operation, path, url, headers, params, httpConfig) { + var interceptors = angular.copy(config.requestInterceptors); + var defaultRequest = config.defaultInterceptor(element, operation, path, url, headers, params, httpConfig); + return _.reduce(interceptors, function(request, interceptor) { + return _.extend(request, interceptor(request.element, operation, + path, url, request.headers, request.params, request.httpConfig)); + }, defaultRequest); + }; - object.addFullRequestInterceptor = function(interceptor) { - config.requestInterceptors.push(interceptor); - return this; - }; + object.addRequestInterceptor = function(interceptor) { + config.requestInterceptors.push(function(elem, operation, path, url, headers, params, httpConfig) { + return { + headers: headers, + params: params, + element: interceptor(elem, operation, path, url), + httpConfig: httpConfig + }; + }); + return this; + }; - object.setFullRequestInterceptor = object.addFullRequestInterceptor; + object.setRequestInterceptor = object.addRequestInterceptor; - config.onBeforeElemRestangularized = config.onBeforeElemRestangularized || function(elem) { - return elem; - }; - object.setOnBeforeElemRestangularized = function(post) { - config.onBeforeElemRestangularized = post; - return this; - }; - - object.setRestangularizePromiseInterceptor = function(interceptor) { - config.restangularizePromiseInterceptor = interceptor; - return this; - }; + object.addFullRequestInterceptor = function(interceptor) { + config.requestInterceptors.push(interceptor); + return this; + }; - /** - * This method is called after an element has been "Restangularized". - * - * It receives the element, a boolean indicating if it's an element or a collection - * and the name of the model - * - */ - config.onElemRestangularized = config.onElemRestangularized || function(elem) { - return elem; - }; - object.setOnElemRestangularized = function(post) { - config.onElemRestangularized = post; - return this; - }; + object.setFullRequestInterceptor = object.addFullRequestInterceptor; - config.shouldSaveParent = config.shouldSaveParent || function() { - return true; - }; - object.setParentless = function(values) { - if (_.isArray(values)) { - config.shouldSaveParent = function(route) { - return !_.includes(values, route); - }; - } else if (_.isBoolean(values)) { - config.shouldSaveParent = function() { - return !values; - }; - } - return this; - }; + config.onBeforeElemRestangularized = config.onBeforeElemRestangularized || function(elem) { + return elem; + }; + object.setOnBeforeElemRestangularized = function(post) { + config.onBeforeElemRestangularized = post; + return this; + }; - /** - * This lets you set a suffix to every request. - * - * For example, if your api requires that for JSon requests you do /users/123.json, you can set that - * in here. - * - * - * By default, the suffix is null - */ - config.suffix = _.isUndefined(config.suffix) ? null : config.suffix; - object.setRequestSuffix = function(newSuffix) { - config.suffix = newSuffix; - return this; - }; + object.setRestangularizePromiseInterceptor = function(interceptor) { + config.restangularizePromiseInterceptor = interceptor; + return this; + }; - /** - * Add element transformers for certain routes. - */ - config.transformers = config.transformers || {}; - config.matchTransformers = config.matchTransformers || []; - object.addElementTransformer = function(type, secondArg, thirdArg) { - var isCollection = null; - var transformer = null; - if (arguments.length === 2) { - transformer = secondArg; - } else { - transformer = thirdArg; - isCollection = secondArg; - } + /** + * This method is called after an element has been "Restangularized". + * + * It receives the element, a boolean indicating if it's an element or a collection + * and the name of the model + * + */ + config.onElemRestangularized = config.onElemRestangularized || function(elem) { + return elem; + }; + object.setOnElemRestangularized = function(post) { + config.onElemRestangularized = post; + return this; + }; - var transformerFn = function(coll, elem) { - if (_.isNull(isCollection) || (coll === isCollection)) { - return transformer(elem); + config.shouldSaveParent = config.shouldSaveParent || function() { + return true; + }; + object.setParentless = function(values) { + if (_.isArray(values)) { + config.shouldSaveParent = function(route) { + return !_.includes(values, route); + }; + } else if (_.isBoolean(values)) { + config.shouldSaveParent = function() { + return !values; + }; } - return elem; + return this; }; - if (_.isRegExp(type)) { - config.matchTransformers.push({ - regexp: type, - transformer: transformerFn - }); - } else { - if (!config.transformers[type]) { - config.transformers[type] = []; + /** + * This lets you set a suffix to every request. + * + * For example, if your api requires that for JSon requests you do /users/123.json, you can set that + * in here. + * + * + * By default, the suffix is null + */ + config.suffix = _.isUndefined(config.suffix) ? null : config.suffix; + object.setRequestSuffix = function(newSuffix) { + config.suffix = newSuffix; + return this; + }; + + /** + * Add element transformers for certain routes. + */ + config.transformers = config.transformers || {}; + config.matchTransformers = config.matchTransformers || []; + object.addElementTransformer = function(type, secondArg, thirdArg) { + var isCollection = null; + var transformer = null; + if (arguments.length === 2) { + transformer = secondArg; + } else { + transformer = thirdArg; + isCollection = secondArg; } - config.transformers[type].push(transformerFn); - } - return object; - }; + var transformerFn = function(coll, elem) { + if (_.isNull(isCollection) || (coll === isCollection)) { + return transformer(elem); + } + return elem; + }; - object.extendCollection = function(route, fn) { - return object.addElementTransformer(route, true, fn); - }; + if (_.isRegExp(type)) { + config.matchTransformers.push({ + regexp: type, + transformer: transformerFn + }); + } else { + if (!config.transformers[type]) { + config.transformers[type] = []; + } + config.transformers[type].push(transformerFn); + } - object.extendModel = function(route, fn) { - return object.addElementTransformer(route, false, fn); - }; + return object; + }; - config.transformElem = function(elem, isCollection, route, Restangular, force) { - if (!force && !config.transformLocalElements && !elem[config.restangularFields.fromServer]) { - return elem; - } + object.extendCollection = function(route, fn) { + return object.addElementTransformer(route, true, fn); + }; - var changedElem = elem; + object.extendModel = function(route, fn) { + return object.addElementTransformer(route, false, fn); + }; - var matchTransformers = config.matchTransformers; - if (matchTransformers) { - _.each(matchTransformers, function (transformer) { - if (route.match(transformer.regexp)) { - changedElem = transformer.transformer(isCollection, changedElem); - } - }); - } + config.transformElem = function(elem, isCollection, route, Restangular, force) { + if (!force && !config.transformLocalElements && !elem[config.restangularFields.fromServer]) { + return elem; + } - var typeTransformers = config.transformers[route]; - if (typeTransformers) { - _.each(typeTransformers, function(transformer) { - changedElem = transformer(isCollection, changedElem); - }); - } - return config.onElemRestangularized(changedElem, isCollection, route, Restangular); - }; + var changedElem = elem; - config.transformLocalElements = _.isUndefined(config.transformLocalElements) ? - false : - config.transformLocalElements; + var matchTransformers = config.matchTransformers; + if (matchTransformers) { + _.each(matchTransformers, function(transformer) { + if (transformer.regexp.test(route)) { + changedElem = transformer.transformer(isCollection, changedElem); + } + }); + } - object.setTransformOnlyServerElements = function(active) { - config.transformLocalElements = !active; - }; + var typeTransformers = config.transformers[route]; + if (typeTransformers) { + _.each(typeTransformers, function(transformer) { + changedElem = transformer(isCollection, changedElem); + }); + } + return config.onElemRestangularized(changedElem, isCollection, route, Restangular); + }; - config.fullResponse = _.isUndefined(config.fullResponse) ? false : config.fullResponse; - object.setFullResponse = function(full) { - config.fullResponse = full; - return this; - }; + config.transformLocalElements = _.isUndefined(config.transformLocalElements) ? + false : + config.transformLocalElements; + object.setTransformOnlyServerElements = function(active) { + config.transformLocalElements = !active; + }; - //Internal values and functions - config.urlCreatorFactory = {}; + config.fullResponse = _.isUndefined(config.fullResponse) ? false : config.fullResponse; + object.setFullResponse = function(full) { + config.fullResponse = full; + return this; + }; - /** - * Base URL Creator. Base prototype for everything related to it - **/ - var BaseCreator = function() { - }; + //Internal values and functions + config.urlCreatorFactory = {}; - BaseCreator.prototype.setConfig = function(config) { - this.config = config; - return this; - }; + /** + * Base URL Creator. Base prototype for everything related to it + **/ - BaseCreator.prototype.parentsArray = function(current) { - var parents = []; - while(current) { - parents.push(current); - current = current[this.config.restangularFields.parentResource]; - } - return parents.reverse(); - }; + var BaseCreator = function() {}; - function RestangularResource(config, $http, url, configurer) { - var resource = {}; - _.each(_.keys(configurer), function(key) { - var value = configurer[key]; + BaseCreator.prototype.setConfig = function(config) { + this.config = config; + return this; + }; - // Add default parameters - value.params = _.extend({}, value.params, config.defaultRequestParams[value.method.toLowerCase()]); - // We don't want the ? if no params are there - if (_.isEmpty(value.params)) { - delete value.params; + BaseCreator.prototype.parentsArray = function(current) { + var parents = []; + while (current) { + parents.push(current); + current = current[this.config.restangularFields.parentResource]; } + return parents.reverse(); + }; - if (config.isSafe(value.method)) { + function RestangularResource(config, $http, url, configurer) { + var resource = {}; + _.each(_.keys(configurer), function(key) { + var value = configurer[key]; - resource[key] = function() { - return $http(_.extend(value, { - url: url - })); - }; + // Add default parameters + value.params = _.extend({}, value.params, config.defaultRequestParams[value.method.toLowerCase()]); + // We don't want the ? if no params are there + if (_.isEmpty(value.params)) { + delete value.params; + } - } else { + if (config.isSafe(value.method)) { - resource[key] = function(data) { - return $http(_.extend(value, { - url: url, - data: data - })); - }; + resource[key] = function() { + return $http(_.extend(value, { + url: url + })); + }; - } - }); + } else { - return resource; - } + resource[key] = function(data) { + return $http(_.extend(value, { + url: url, + data: data + })); + }; - BaseCreator.prototype.resource = function(current, $http, localHttpConfig, callHeaders, callParams, what, etag,operation) { + } + }); - var params = _.defaults(callParams || {}, this.config.defaultRequestParams.common); - var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders); + return resource; + } - if (etag) { - if (!config.isSafe(operation)) { - headers['If-Match'] = etag; - } else { - headers['If-None-Match'] = etag; + BaseCreator.prototype.resource = function(current, $http, localHttpConfig, callHeaders, callParams, what, etag, operation) { + + var params = _.defaults(callParams || {}, this.config.defaultRequestParams.common); + var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders); + + if (etag) { + if (!config.isSafe(operation)) { + headers['If-Match'] = etag; + } else { + headers['If-None-Match'] = etag; + } } - } - var url = this.base(current); + var url = this.base(current); - if (what || what === 0) { - var add = ''; - if (!/\/$/.test(url)) { - add += '/'; + if (what || what === 0) { + var add = ''; + if (!/\/$/.test(url)) { + add += '/'; + } + add += what; + url += add; } - add += what; - url += add; - } - if (this.config.suffix && - url.indexOf(this.config.suffix, url.length - this.config.suffix.length) === -1 && - !this.config.getUrlFromElem(current)) { + if (this.config.suffix && + url.indexOf(this.config.suffix, url.length - this.config.suffix.length) === -1 && + !this.config.getUrlFromElem(current)) { url += this.config.suffix; - } - - current[this.config.restangularFields.httpConfig] = undefined; + } - return RestangularResource(this.config, $http, url, { - getList: this.config.withHttpValues(localHttpConfig, - {method: 'GET', - params: params, - headers: headers}), + current[this.config.restangularFields.httpConfig] = undefined; - get: this.config.withHttpValues(localHttpConfig, - {method: 'GET', - params: params, - headers: headers}), + return RestangularResource(this.config, $http, url, { + getList: this.config.withHttpValues(localHttpConfig, { + method: 'GET', + params: params, + headers: headers + }), - jsonp: this.config.withHttpValues(localHttpConfig, - {method: 'jsonp', - params: params, - headers: headers}), + get: this.config.withHttpValues(localHttpConfig, { + method: 'GET', + params: params, + headers: headers + }), - put: this.config.withHttpValues(localHttpConfig, - {method: 'PUT', - params: params, - headers: headers}), + jsonp: this.config.withHttpValues(localHttpConfig, { + method: 'jsonp', + params: params, + headers: headers + }), - post: this.config.withHttpValues(localHttpConfig, - {method: 'POST', - params: params, - headers: headers}), + put: this.config.withHttpValues(localHttpConfig, { + method: 'PUT', + params: params, + headers: headers + }), - remove: this.config.withHttpValues(localHttpConfig, - {method: 'DELETE', - params: params, - headers: headers}), + post: this.config.withHttpValues(localHttpConfig, { + method: 'POST', + params: params, + headers: headers + }), - head: this.config.withHttpValues(localHttpConfig, - {method: 'HEAD', - params: params, - headers: headers}), + remove: this.config.withHttpValues(localHttpConfig, { + method: 'DELETE', + params: params, + headers: headers + }), - trace: this.config.withHttpValues(localHttpConfig, - {method: 'TRACE', - params: params, - headers: headers}), + head: this.config.withHttpValues(localHttpConfig, { + method: 'HEAD', + params: params, + headers: headers + }), - options: this.config.withHttpValues(localHttpConfig, - {method: 'OPTIONS', - params: params, - headers: headers}), + trace: this.config.withHttpValues(localHttpConfig, { + method: 'TRACE', + params: params, + headers: headers + }), - patch: this.config.withHttpValues(localHttpConfig, - {method: 'PATCH', - params: params, - headers: headers}) - }); - }; + options: this.config.withHttpValues(localHttpConfig, { + method: 'OPTIONS', + params: params, + headers: headers + }), - /** - * This is the Path URL creator. It uses Path to show Hierarchy in the Rest API. - * This means that if you have an Account that then has a set of Buildings, a URL to a building - * would be /accounts/123/buildings/456 - **/ - var Path = function() { - }; + patch: this.config.withHttpValues(localHttpConfig, { + method: 'PATCH', + params: params, + headers: headers + }) + }); + }; - Path.prototype = new BaseCreator(); + /** + * This is the Path URL creator. It uses Path to show Hierarchy in the Rest API. + * This means that if you have an Account that then has a set of Buildings, a URL to a building + * would be /accounts/123/buildings/456 + **/ + var Path = function() {}; - Path.prototype.normalizeUrl = function (url){ - var parts = /((?:http[s]?:)?\/\/)?(.*)?/.exec(url); - parts[2] = parts[2].replace(/[\\\/]+/g, '/'); - return (typeof parts[1] !== 'undefined')? parts[1] + parts[2] : parts[2]; - }; + Path.prototype = new BaseCreator(); - Path.prototype.base = function(current) { - var __this = this; - return _.reduce(this.parentsArray(current), function(acum, elem) { - var elemUrl; - var elemSelfLink = __this.config.getUrlFromElem(elem); - if (elemSelfLink) { - if (__this.config.isAbsoluteUrl(elemSelfLink)) { - return elemSelfLink; - } else { - elemUrl = elemSelfLink; - } - } else { - elemUrl = elem[__this.config.restangularFields.route]; + Path.prototype.normalizeUrl = function(url) { + var parts = /((?:http[s]?:)?\/\/)?(.*)?/.exec(url); + parts[2] = parts[2].replace(/[\\\/]+/g, '/'); + return (typeof parts[1] !== 'undefined') ? parts[1] + parts[2] : parts[2]; + }; - if (elem[__this.config.restangularFields.restangularCollection]) { - var ids = elem[__this.config.restangularFields.ids]; - if (ids) { - elemUrl += '/' + ids.join(','); - } - } else { - var elemId; - if (__this.config.useCannonicalId) { - elemId = __this.config.getCannonicalIdFromElem(elem); + Path.prototype.base = function(current) { + var __this = this; + return _.reduce(this.parentsArray(current), function(acum, elem) { + var elemUrl; + var elemSelfLink = __this.config.getUrlFromElem(elem); + if (elemSelfLink) { + if (__this.config.isAbsoluteUrl(elemSelfLink)) { + return elemSelfLink; } else { - elemId = __this.config.getIdFromElem(elem); + elemUrl = elemSelfLink; } + } else { + elemUrl = elem[__this.config.restangularFields.route]; - if (config.isValidId(elemId) && !elem.singleOne) { - elemUrl += '/' + (__this.config.encodeIds ? encodeURIComponent(elemId) : elemId); + if (elem[__this.config.restangularFields.restangularCollection]) { + var ids = elem[__this.config.restangularFields.ids]; + if (ids) { + elemUrl += '/' + ids.join(','); + } + } else { + var elemId; + if (__this.config.useCannonicalId) { + elemId = __this.config.getCannonicalIdFromElem(elem); + } else { + elemId = __this.config.getIdFromElem(elem); + } + + if (config.isValidId(elemId) && !elem.singleOne) { + elemUrl += '/' + (__this.config.encodeIds ? encodeURIComponent(elemId) : elemId); + } } } - } - acum = acum.replace(/\/$/, '') + '/' + elemUrl; - return __this.normalizeUrl(acum); + acum = acum.replace(/\/$/, '') + '/' + elemUrl; + return __this.normalizeUrl(acum); - }, this.config.baseUrl); - }; + }, this.config.baseUrl); + }; - Path.prototype.fetchUrl = function(current, what) { - var baseUrl = this.base(current); - if (what) { - baseUrl += '/' + what; - } - return baseUrl; - }; + Path.prototype.fetchUrl = function(current, what) { + var baseUrl = this.base(current); + if (what) { + baseUrl += '/' + what; + } + return baseUrl; + }; - Path.prototype.fetchRequestedUrl = function(current, what) { - var url = this.fetchUrl(current, what); - var params = current[config.restangularFields.reqParams]; - - // From here on and until the end of fetchRequestedUrl, - // the code has been kindly borrowed from angular.js - // The reason for such code bloating is coherence: - // If the user were to use this for cache management, the - // serialization of parameters would need to be identical - // to the one done by angular for cache keys to match. - function sortedKeys(obj) { - var keys = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - keys.push(key); + Path.prototype.fetchRequestedUrl = function(current, what) { + var url = this.fetchUrl(current, what); + var params = current[config.restangularFields.reqParams]; + + // From here on and until the end of fetchRequestedUrl, + // the code has been kindly borrowed from angular.js + // The reason for such code bloating is coherence: + // If the user were to use this for cache management, the + // serialization of parameters would need to be identical + // to the one done by angular for cache keys to match. + function sortedKeys(obj) { + var keys = []; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + keys.push(key); + } } + return keys.sort(); } - return keys.sort(); - } - function forEachSorted(obj, iterator, context) { - var keys = sortedKeys(obj); - for ( var i = 0; i < keys.length; i++) { - iterator.call(context, obj[keys[i]], keys[i]); + function forEachSorted(obj, iterator, context) { + var keys = sortedKeys(obj); + for (var i = 0; i < keys.length; i++) { + iterator.call(context, obj[keys[i]], keys[i]); + } + return keys; } - return keys; - } - - function encodeUriQuery(val, pctEncodeSpaces) { - return encodeURIComponent(val). - replace(/%40/gi, '@'). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); - } - if (!params) { return url + (this.config.suffix || ''); } + function encodeUriQuery(val, pctEncodeSpaces) { + return encodeURIComponent(val). + replace(/%40/gi, '@'). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); + } - var parts = []; - forEachSorted(params, function(value, key) { - if (value === null || value === undefined) { return; } - if (!angular.isArray(value)) { value = [value]; } + if (!params) { + return url + (this.config.suffix || ''); + } - angular.forEach(value, function(v) { - if (angular.isObject(v)) { - v = angular.toJson(v); + var parts = []; + forEachSorted(params, function(value, key) { + if (value === null || value === undefined) { + return; + } + if (!angular.isArray(value)) { + value = [value]; } - parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); + + angular.forEach(value, function(v) { + if (angular.isObject(v)) { + v = angular.toJson(v); + } + parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); + }); }); - }); - return url + (this.config.suffix || '') + ((url.indexOf('?') === -1) ? '?' : '&') + parts.join('&'); + return url + (this.config.suffix || '') + ((url.indexOf('?') === -1) ? '?' : '&') + parts.join('&'); + }; + + config.urlCreatorFactory.path = Path; }; - config.urlCreatorFactory.path = Path; - }; + var globalConfiguration = {}; - var globalConfiguration = {}; + Configurer.init(this, globalConfiguration); - Configurer.init(this, globalConfiguration); + this.$get = ['$http', '$q', function($http, $q) { - this.$get = ['$http', '$q', function($http, $q) { + function createServiceForConfiguration(config) { + var service = {}; - function createServiceForConfiguration(config) { - var service = {}; + var urlHandler = new config.urlCreatorFactory[config.urlCreator](); + urlHandler.setConfig(config); - var urlHandler = new config.urlCreatorFactory[config.urlCreator](); - urlHandler.setConfig(config); + function restangularizeBase(parent, elem, route, reqParams, fromServer) { + elem[config.restangularFields.route] = route; + elem[config.restangularFields.getRestangularUrl] = _.bind(urlHandler.fetchUrl, urlHandler, elem); + elem[config.restangularFields.getRequestedUrl] = _.bind(urlHandler.fetchRequestedUrl, urlHandler, elem); + elem[config.restangularFields.addRestangularMethod] = _.bind(addRestangularMethodFunction, elem); + elem[config.restangularFields.clone] = _.bind(copyRestangularizedElement, elem, elem); + elem[config.restangularFields.reqParams] = _.isEmpty(reqParams) ? null : reqParams; + elem[config.restangularFields.withHttpConfig] = _.bind(withHttpConfig, elem); + elem[config.restangularFields.plain] = _.bind(stripRestangular, elem, elem); - function restangularizeBase(parent, elem, route, reqParams, fromServer) { - elem[config.restangularFields.route] = route; - elem[config.restangularFields.getRestangularUrl] = _.bind(urlHandler.fetchUrl, urlHandler, elem); - elem[config.restangularFields.getRequestedUrl] = _.bind(urlHandler.fetchRequestedUrl, urlHandler, elem); - elem[config.restangularFields.addRestangularMethod] = _.bind(addRestangularMethodFunction, elem); - elem[config.restangularFields.clone] = _.bind(copyRestangularizedElement, elem, elem); - elem[config.restangularFields.reqParams] = _.isEmpty(reqParams) ? null : reqParams; - elem[config.restangularFields.withHttpConfig] = _.bind(withHttpConfig, elem); - elem[config.restangularFields.plain] = _.bind(stripRestangular, elem, elem); + // Tag element as restangularized + elem[config.restangularFields.restangularized] = true; - // Tag element as restangularized - elem[config.restangularFields.restangularized] = true; + // RequestLess connection + elem[config.restangularFields.one] = _.bind(one, elem, elem); + elem[config.restangularFields.all] = _.bind(all, elem, elem); + elem[config.restangularFields.several] = _.bind(several, elem, elem); + elem[config.restangularFields.oneUrl] = _.bind(oneUrl, elem, elem); + elem[config.restangularFields.allUrl] = _.bind(allUrl, elem, elem); - // RequestLess connection - elem[config.restangularFields.one] = _.bind(one, elem, elem); - elem[config.restangularFields.all] = _.bind(all, elem, elem); - elem[config.restangularFields.several] = _.bind(several, elem, elem); - elem[config.restangularFields.oneUrl] = _.bind(oneUrl, elem, elem); - elem[config.restangularFields.allUrl] = _.bind(allUrl, elem, elem); + elem[config.restangularFields.fromServer] = !!fromServer; - elem[config.restangularFields.fromServer] = !!fromServer; + if (parent && config.shouldSaveParent(route)) { + var parentId = config.getIdFromElem(parent); + var parentUrl = config.getUrlFromElem(parent); - if (parent && config.shouldSaveParent(route)) { - var parentId = config.getIdFromElem(parent); - var parentUrl = config.getUrlFromElem(parent); + var restangularFieldsForParent = _.union( + _.values(_.pick(config.restangularFields, ['route', 'singleOne', 'parentResource'])), + config.extraFields + ); + var parentResource = _.pick(parent, restangularFieldsForParent); - var restangularFieldsForParent = _.union( - _.values( _.pick(config.restangularFields, ['route', 'singleOne', 'parentResource']) ), - config.extraFields - ); - var parentResource = _.pick(parent, restangularFieldsForParent); + if (config.isValidId(parentId)) { + config.setIdToElem(parentResource, parentId, route); + } + if (config.isValidId(parentUrl)) { + config.setUrlToElem(parentResource, parentUrl, route); + } - if (config.isValidId(parentId)) { - config.setIdToElem(parentResource, parentId, route); - } - if (config.isValidId(parentUrl)) { - config.setUrlToElem(parentResource, parentUrl, route); + elem[config.restangularFields.parentResource] = parentResource; + } else { + elem[config.restangularFields.parentResource] = null; } - - elem[config.restangularFields.parentResource] = parentResource; - } else { - elem[config.restangularFields.parentResource] = null; + return elem; } - return elem; - } - function one(parent, route, id, singleOne) { - var error; - if (_.isNumber(route) || _.isNumber(parent)) { - error = 'You\'re creating a Restangular entity with the number '; - error += 'instead of the route or the parent. For example, you can\'t call .one(12).'; - throw new Error(error); - } - if (_.isUndefined(route)) { - error = 'You\'re creating a Restangular entity either without the path. '; - error += 'For example you can\'t call .one(). Please check if your arguments are valid.'; - throw new Error(error); + function one(parent, route, id, singleOne) { + var error; + if (_.isNumber(route) || _.isNumber(parent)) { + error = 'You\'re creating a Restangular entity with the number '; + error += 'instead of the route or the parent. For example, you can\'t call .one(12).'; + throw new Error(error); + } + if (_.isUndefined(route)) { + error = 'You\'re creating a Restangular entity either without the path. '; + error += 'For example you can\'t call .one(). Please check if your arguments are valid.'; + throw new Error(error); + } + var elem = {}; + config.setIdToElem(elem, id, route); + config.setFieldToElem(config.restangularFields.singleOne, elem, singleOne); + return restangularizeElem(parent, elem, route, false); } - var elem = {}; - config.setIdToElem(elem, id, route); - config.setFieldToElem(config.restangularFields.singleOne, elem, singleOne); - return restangularizeElem(parent, elem , route, false); - } - function all(parent, route) { - return restangularizeCollection(parent, [] , route, false); - } + function all(parent, route) { + return restangularizeCollection(parent, [], route, false); + } - function several(parent, route /*, ids */) { - var collection = []; - collection[config.restangularFields.ids] = Array.prototype.splice.call(arguments, 2); - return restangularizeCollection(parent, collection , route, false); - } + function several(parent, route /*, ids */ ) { + var collection = []; + collection[config.restangularFields.ids] = Array.prototype.splice.call(arguments, 2); + return restangularizeCollection(parent, collection, route, false); + } - function oneUrl(parent, route, url) { - if (!route) { - throw new Error('Route is mandatory when creating new Restangular objects.'); + function oneUrl(parent, route, url) { + if (!route) { + throw new Error('Route is mandatory when creating new Restangular objects.'); + } + var elem = {}; + config.setUrlToElem(elem, url, route); + return restangularizeElem(parent, elem, route, false); } - var elem = {}; - config.setUrlToElem(elem, url, route); - return restangularizeElem(parent, elem , route, false); - } - function allUrl(parent, route, url) { - if (!route) { - throw new Error('Route is mandatory when creating new Restangular objects.'); + function allUrl(parent, route, url) { + if (!route) { + throw new Error('Route is mandatory when creating new Restangular objects.'); + } + var elem = {}; + config.setUrlToElem(elem, url, route); + return restangularizeCollection(parent, elem, route, false); } - var elem = {}; - config.setUrlToElem(elem, url, route); - return restangularizeCollection(parent, elem , route, false); - } - // Promises - function restangularizePromise(promise, isCollection, valueToFill) { - promise.call = _.bind(promiseCall, promise); - promise.get = _.bind(promiseGet, promise); - promise[config.restangularFields.restangularCollection] = isCollection; - if (isCollection) { + // Promises + function restangularizePromise(promise, isCollection, valueToFill) { + promise.call = _.bind(promiseCall, promise); + promise.get = _.bind(promiseGet, promise); + promise[config.restangularFields.restangularCollection] = isCollection; + if (isCollection) { promise.push = _.bind(promiseCall, promise, 'push'); + } + promise.$object = valueToFill; + if (config.restangularizePromiseInterceptor) { + config.restangularizePromiseInterceptor(promise); + } + return promise; } - promise.$object = valueToFill; - if (config.restangularizePromiseInterceptor) { - config.restangularizePromiseInterceptor(promise); - } - return promise; - } - - function promiseCall(method) { - var deferred = $q.defer(); - var callArgs = arguments; - var filledValue = {}; - this.then(function(val) { - var params = Array.prototype.slice.call(callArgs, 1); - var func = val[method]; - func.apply(val, params); - filledValue = val; - deferred.resolve(val); - }); - return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue); - } - - function promiseGet(what) { - var deferred = $q.defer(); - var filledValue = {}; - this.then(function(val) { - filledValue = val[what]; - deferred.resolve(filledValue); - }); - return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue); - } - - function resolvePromise(deferred, response, data, filledValue) { - _.extend(filledValue, data); - - // Trigger the full response interceptor. - if (config.fullResponse) { - return deferred.resolve(_.extend(response, { - data: data - })); - } else { - deferred.resolve(data); - } - } - - // Elements - function stripRestangular(elem) { - if (_.isArray(elem)) { - var array = []; - _.each(elem, function(value) { - array.push(config.isRestangularized(value) ? stripRestangular(value) : value); + function promiseCall(method) { + var deferred = $q.defer(); + var callArgs = arguments; + var filledValue = {}; + this.then(function(val) { + var params = Array.prototype.slice.call(callArgs, 1); + var func = val[method]; + func.apply(val, params); + filledValue = val; + deferred.resolve(val); }); - return array; - } else { - return _.omit(elem, _.values(_.omit(config.restangularFields, 'id'))); + return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue); } - } - function addCustomOperation(elem) { - elem[config.restangularFields.customOperation] = _.bind(customFunction, elem); - var requestMethods = { get: customFunction, delete: customFunction }; - _.each(['put', 'patch', 'post'], function(name) { - requestMethods[name] = function(operation, elem, path, params, headers) { - return _.bind(customFunction, this)(operation, path, params, headers, elem); - }; - }); - _.each(requestMethods, function(requestFunc, name) { - var callOperation = name === 'delete' ? 'remove' : name; - _.each(['do', 'custom'], function(alias) { - elem[alias + name.toUpperCase()] = _.bind(requestFunc, elem, callOperation); + function promiseGet(what) { + var deferred = $q.defer(); + var filledValue = {}; + this.then(function(val) { + filledValue = val[what]; + deferred.resolve(filledValue); }); - }); - elem[config.restangularFields.customGETLIST] = _.bind(fetchFunction, elem); - elem[config.restangularFields.doGETLIST] = elem[config.restangularFields.customGETLIST]; - } + return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue); + } - function copyRestangularizedElement(fromElement, toElement) { - var copiedElement = angular.copy(fromElement, toElement); - return restangularizeElem(copiedElement[config.restangularFields.parentResource], - copiedElement, copiedElement[config.restangularFields.route], copiedElement[config.restangularFields.fromServer]); - } + function resolvePromise(deferred, response, data, filledValue) { + _.extend(filledValue, data); - function restangularizeElem(parent, element, route, fromServer, collection, reqParams) { - var elem = config.onBeforeElemRestangularized(element, false, route); + // Trigger the full response interceptor. + if (config.fullResponse) { + return deferred.resolve(_.extend(response, { + data: data + })); + } else { + deferred.resolve(data); + } + } - var localElem = restangularizeBase(parent, elem, route, reqParams, fromServer); - if (config.useCannonicalId) { - localElem[config.restangularFields.cannonicalId] = config.getIdFromElem(localElem); + // Elements + function stripRestangular(elem) { + if (_.isArray(elem)) { + var array = []; + _.each(elem, function(value) { + array.push(config.isRestangularized(value) ? stripRestangular(value) : value); + }); + return array; + } else { + return _.omit(elem, _.values(_.omit(config.restangularFields, 'id'))); + } } - if (collection) { - localElem[config.restangularFields.getParentList] = function() { - return collection; + function addCustomOperation(elem) { + elem[config.restangularFields.customOperation] = _.bind(customFunction, elem); + var requestMethods = { + get: customFunction, + delete: customFunction }; + _.each(['put', 'patch', 'post'], function(name) { + requestMethods[name] = function(operation, elem, path, params, headers) { + return _.bind(customFunction, this)(operation, path, params, headers, elem); + }; + }); + _.each(requestMethods, function(requestFunc, name) { + var callOperation = name === 'delete' ? 'remove' : name; + _.each(['do', 'custom'], function(alias) { + elem[alias + name.toUpperCase()] = _.bind(requestFunc, elem, callOperation); + }); + }); + elem[config.restangularFields.customGETLIST] = _.bind(fetchFunction, elem); + elem[config.restangularFields.doGETLIST] = elem[config.restangularFields.customGETLIST]; } - localElem[config.restangularFields.restangularCollection] = false; - localElem[config.restangularFields.get] = _.bind(getFunction, localElem); - localElem[config.restangularFields.getList] = _.bind(fetchFunction, localElem); - localElem[config.restangularFields.put] = _.bind(putFunction, localElem); - localElem[config.restangularFields.post] = _.bind(postFunction, localElem); - localElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem); - localElem[config.restangularFields.head] = _.bind(headFunction, localElem); - localElem[config.restangularFields.trace] = _.bind(traceFunction, localElem); - localElem[config.restangularFields.options] = _.bind(optionsFunction, localElem); - localElem[config.restangularFields.patch] = _.bind(patchFunction, localElem); - localElem[config.restangularFields.save] = _.bind(save, localElem); - - addCustomOperation(localElem); - return config.transformElem(localElem, false, route, service, true); - } - - function restangularizeCollection(parent, element, route, fromServer, reqParams) { - var elem = config.onBeforeElemRestangularized(element, true, route); - - var localElem = restangularizeBase(parent, elem, route, reqParams, fromServer); - localElem[config.restangularFields.restangularCollection] = true; - localElem[config.restangularFields.post] = _.bind(postFunction, localElem, null); - localElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem); - localElem[config.restangularFields.head] = _.bind(headFunction, localElem); - localElem[config.restangularFields.trace] = _.bind(traceFunction, localElem); - localElem[config.restangularFields.putElement] = _.bind(putElementFunction, localElem); - localElem[config.restangularFields.options] = _.bind(optionsFunction, localElem); - localElem[config.restangularFields.patch] = _.bind(patchFunction, localElem); - localElem[config.restangularFields.get] = _.bind(getById, localElem); - localElem[config.restangularFields.getList] = _.bind(fetchFunction, localElem, null); - - addCustomOperation(localElem); - return config.transformElem(localElem, true, route, service, true); - } - - function restangularizeCollectionAndElements(parent, element, route, fromServer) { - var collection = restangularizeCollection(parent, element, route, fromServer); - _.each(collection, function(elem) { - if (elem) { - restangularizeElem(parent, elem, route, fromServer); + function copyRestangularizedElement(element) { + var copiedElement = angular.copy(element); + + // check if we're dealing with a collection (i.e. an array) + // and restangularize the element using the proper restangularizer, + // element / collection + if (_.isArray(element)) { + return restangularizeCollection( + element[config.restangularFields.parentResource], + copiedElement, + element[config.restangularFields.route], + element[config.restangularFields.fromServer], + element[config.restangularFields.reqParams] + ); } - }); - return collection; - } - - function getById(id, reqParams, headers){ - return this.customGET(id.toString(), reqParams, headers); - } - function putElementFunction(idx, params, headers) { - var __this = this; - var elemToPut = this[idx]; - var deferred = $q.defer(); - var filledArray = []; - filledArray = config.transformElem(filledArray, true, elemToPut[config.restangularFields.route], service); - elemToPut.put(params, headers).then(function(serverElem) { - var newArray = copyRestangularizedElement(__this); - newArray[idx] = serverElem; - filledArray = newArray; - deferred.resolve(newArray); - }, function(response) { - deferred.reject(response); - }); - - return restangularizePromise(deferred.promise, true, filledArray); - } - - function parseResponse(resData, operation, route, fetchUrl, response, deferred) { - var data = config.responseExtractor(resData, operation, route, fetchUrl, response, deferred); - var etag = response.headers('ETag'); - if (data && etag) { - data[config.restangularFields.etag] = etag; + // not a collection, restangularize it as an element + return restangularizeElem( + element[config.restangularFields.parentResource], + copiedElement, + element[config.restangularFields.route], + element[config.restangularFields.fromServer], + element[config.restangularFields.restangularCollection], + element[config.restangularFields.reqParams] + ); } - return data; - } + function restangularizeElem(parent, element, route, fromServer, collection, reqParams) { + var elem = config.onBeforeElemRestangularized(element, false, route); - function fetchFunction(what, reqParams, headers) { - var __this = this; - var deferred = $q.defer(); - var operation = 'getList'; - var url = urlHandler.fetchUrl(this, what); - var whatFetched = what || __this[config.restangularFields.route]; + var localElem = restangularizeBase(parent, elem, route, reqParams, fromServer); - var request = config.fullRequestInterceptor(null, operation, - whatFetched, url, headers || {}, reqParams || {}, this[config.restangularFields.httpConfig] || {}); - - var filledArray = []; - filledArray = config.transformElem(filledArray, true, whatFetched, service); + if (config.useCannonicalId) { + localElem[config.restangularFields.cannonicalId] = config.getIdFromElem(localElem); + } - var method = 'getList'; + if (collection) { + localElem[config.restangularFields.getParentList] = function() { + return collection; + }; + } - if (config.jsonp) { - method = 'jsonp'; + localElem[config.restangularFields.restangularCollection] = false; + localElem[config.restangularFields.get] = _.bind(getFunction, localElem); + localElem[config.restangularFields.getList] = _.bind(fetchFunction, localElem); + localElem[config.restangularFields.put] = _.bind(putFunction, localElem); + localElem[config.restangularFields.post] = _.bind(postFunction, localElem); + localElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem); + localElem[config.restangularFields.head] = _.bind(headFunction, localElem); + localElem[config.restangularFields.trace] = _.bind(traceFunction, localElem); + localElem[config.restangularFields.options] = _.bind(optionsFunction, localElem); + localElem[config.restangularFields.patch] = _.bind(patchFunction, localElem); + localElem[config.restangularFields.save] = _.bind(save, localElem); + + addCustomOperation(localElem); + return config.transformElem(localElem, false, route, service, true); } - var okCallback = function(response) { - var resData = response.data; - var fullParams = response.config.params; - var data = parseResponse(resData, operation, whatFetched, url, response, deferred); - - // support empty response for getList() calls (some APIs respond with 204 and empty body) - if (_.isUndefined(data) || '' === data) { - data = []; - } - if (!_.isArray(data)) { - throw new Error('Response for getList SHOULD be an array and not an object or something else'); - } - - if (true === config.plainByDefault) { - return resolvePromise(deferred, response, data, filledArray); - } + function restangularizeCollection(parent, element, route, fromServer, reqParams) { + var elem = config.onBeforeElemRestangularized(element, true, route); + + var localElem = restangularizeBase(parent, elem, route, reqParams, fromServer); + localElem[config.restangularFields.restangularCollection] = true; + localElem[config.restangularFields.post] = _.bind(postFunction, localElem, null); + localElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem); + localElem[config.restangularFields.head] = _.bind(headFunction, localElem); + localElem[config.restangularFields.trace] = _.bind(traceFunction, localElem); + localElem[config.restangularFields.putElement] = _.bind(putElementFunction, localElem); + localElem[config.restangularFields.options] = _.bind(optionsFunction, localElem); + localElem[config.restangularFields.patch] = _.bind(patchFunction, localElem); + localElem[config.restangularFields.get] = _.bind(getById, localElem); + localElem[config.restangularFields.getList] = _.bind(fetchFunction, localElem, null); + + addCustomOperation(localElem); + return config.transformElem(localElem, true, route, service, true); + } - var processedData = _.map(data, function(elem) { - if (!__this[config.restangularFields.restangularCollection]) { - return restangularizeElem(__this, elem, what, true, data); - } else { - return restangularizeElem(__this[config.restangularFields.parentResource], - elem, __this[config.restangularFields.route], true, data); + function restangularizeCollectionAndElements(parent, element, route, fromServer) { + var collection = restangularizeCollection(parent, element, route, fromServer); + _.each(collection, function(elem) { + if (elem) { + restangularizeElem(parent, elem, route, fromServer); } }); + return collection; + } - processedData = _.extend(data, processedData); - - if (!__this[config.restangularFields.restangularCollection]) { - resolvePromise( - deferred, - response, - restangularizeCollection( - __this, - processedData, - what, - true, - fullParams - ), - filledArray - ); - } else { - resolvePromise( - deferred, - response, - restangularizeCollection( - __this[config.restangularFields.parentResource], - processedData, - __this[config.restangularFields.route], - true, - fullParams - ), - filledArray - ); - } - }; + function getById(id, reqParams, headers) { + return this.customGET(id.toString(), reqParams, headers); + } - urlHandler.resource(this, $http, request.httpConfig, request.headers, request.params, what, - this[config.restangularFields.etag], operation)[method]().then(okCallback, function error(response) { - if (response.status === 304 && __this[config.restangularFields.restangularCollection]) { - resolvePromise(deferred, response, __this, filledArray); - } else if ( _.every(config.errorInterceptors, function(cb) { return cb(response, deferred, okCallback) !== false; }) ) { - // triggered if no callback returns false + function putElementFunction(idx, params, headers) { + var __this = this; + var elemToPut = this[idx]; + var deferred = $q.defer(); + var filledArray = []; + filledArray = config.transformElem(filledArray, true, elemToPut[config.restangularFields.route], service); + elemToPut.put(params, headers).then(function(serverElem) { + var newArray = copyRestangularizedElement(__this); + newArray[idx] = serverElem; + filledArray = newArray; + deferred.resolve(newArray); + }, function(response) { deferred.reject(response); - } - }); - - return restangularizePromise(deferred.promise, true, filledArray); - } + }); - function withHttpConfig(httpConfig) { - this[config.restangularFields.httpConfig] = httpConfig; - return this; - } + return restangularizePromise(deferred.promise, true, filledArray); + } - function save(params, headers) { - if (this[config.restangularFields.fromServer]) { - return this[config.restangularFields.put](params, headers); - } else { - return _.bind(elemFunction, this)('post', undefined, params, undefined, headers); + function parseResponse(resData, operation, route, fetchUrl, response, deferred) { + var data = config.responseExtractor(resData, operation, route, fetchUrl, response, deferred); + var etag = response.headers('ETag'); + if (data && etag) { + data[config.restangularFields.etag] = etag; + } + return data; } - } - function elemFunction(operation, what, params, obj, headers) { - var __this = this; - var deferred = $q.defer(); - var resParams = params || {}; - var route = what || this[config.restangularFields.route]; - var fetchUrl = urlHandler.fetchUrl(this, what); - var callObj = obj || this; - // fallback to etag on restangular object (since for custom methods we probably don't explicitly specify the etag field) - var etag = callObj[config.restangularFields.etag] || (operation !== 'post' ? this[config.restangularFields.etag] : null); + function fetchFunction(what, reqParams, headers) { + var __this = this; + var deferred = $q.defer(); + var operation = 'getList'; + var url = urlHandler.fetchUrl(this, what); + var whatFetched = what || __this[config.restangularFields.route]; - if (_.isObject(callObj) && config.isRestangularized(callObj)) { - callObj = stripRestangular(callObj); - } - var request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl, - headers || {}, resParams || {}, this[config.restangularFields.httpConfig] || {}); + var request = config.fullRequestInterceptor(null, operation, + whatFetched, url, headers || {}, reqParams || {}, this[config.restangularFields.httpConfig] || {}); + + var filledArray = []; + filledArray = config.transformElem(filledArray, true, whatFetched, service); - var filledObject = {}; - filledObject = config.transformElem(filledObject, false, route, service); + var method = 'getList'; - var okCallback = function(response) { - var resData = response.data; - var fullParams = response.config.params; - var elem = parseResponse(resData, operation, route, fetchUrl, response, deferred); + if (config.jsonp) { + method = 'jsonp'; + } - // accept 0 as response - if (elem !== null && elem !== undefined && elem !== '') { - var data; + var okCallback = function(response) { + var resData = response.data; + var fullParams = response.config.params; + var data = parseResponse(resData, operation, whatFetched, url, response, deferred); + + // support empty response for getList() calls (some APIs respond with 204 and empty body) + if (_.isUndefined(data) || '' === data) { + data = []; + } + if (!_.isArray(data)) { + throw new Error('Response for getList SHOULD be an array and not an object or something else'); + } if (true === config.plainByDefault) { - return resolvePromise(deferred, response, elem, filledObject); + return resolvePromise(deferred, response, data, filledArray); } - if (operation === 'post' && !__this[config.restangularFields.restangularCollection]) { - data = restangularizeElem( - __this[config.restangularFields.parentResource], - elem, - route, - true, - null, - fullParams + var processedData = _.map(data, function(elem) { + if (!__this[config.restangularFields.restangularCollection]) { + return restangularizeElem(__this, elem, what, true, data); + } else { + return restangularizeElem(__this[config.restangularFields.parentResource], + elem, __this[config.restangularFields.route], true, data); + } + }); + + processedData = _.extend(data, processedData); + + if (!__this[config.restangularFields.restangularCollection]) { + resolvePromise( + deferred, + response, + restangularizeCollection( + __this, + processedData, + what, + true, + fullParams + ), + filledArray ); - resolvePromise(deferred, response, data, filledObject); } else { - data = restangularizeElem( - __this[config.restangularFields.parentResource], - elem, - __this[config.restangularFields.route], - true, - null, - fullParams + resolvePromise( + deferred, + response, + restangularizeCollection( + __this[config.restangularFields.parentResource], + processedData, + __this[config.restangularFields.route], + true, + fullParams + ), + filledArray ); + } + }; - data[config.restangularFields.singleOne] = __this[config.restangularFields.singleOne]; - resolvePromise(deferred, response, data, filledObject); + urlHandler.resource(this, $http, request.httpConfig, request.headers, request.params, what, + this[config.restangularFields.etag], operation)[method]().then(okCallback, function error(response) { + if (response.status === 304 && __this[config.restangularFields.restangularCollection]) { + resolvePromise(deferred, response, __this, filledArray); + } else if (_.every(config.errorInterceptors, function(cb) { + return cb(response, deferred, okCallback) !== false; + })) { + // triggered if no callback returns false + deferred.reject(response); } + }); + + return restangularizePromise(deferred.promise, true, filledArray); + } + function withHttpConfig(httpConfig) { + this[config.restangularFields.httpConfig] = httpConfig; + return this; + } + + function save(params, headers) { + if (this[config.restangularFields.fromServer]) { + return this[config.restangularFields.put](params, headers); } else { - resolvePromise(deferred, response, undefined, filledObject); + return _.bind(elemFunction, this)('post', undefined, params, undefined, headers); } - }; + } - var errorCallback = function(response) { - if (response.status === 304 && config.isSafe(operation)) { - resolvePromise(deferred, response, __this, filledObject); - } else if ( _.every(config.errorInterceptors, function(cb) { return cb(response, deferred, okCallback) !== false; }) ) { - // triggered if no callback returns false - deferred.reject(response); + function elemFunction(operation, what, params, obj, headers) { + var __this = this; + var deferred = $q.defer(); + var resParams = params || {}; + var route = what || this[config.restangularFields.route]; + var fetchUrl = urlHandler.fetchUrl(this, what); + + var callObj = obj || this; + // fallback to etag on restangular object (since for custom methods we probably don't explicitly specify the etag field) + var etag = callObj[config.restangularFields.etag] || (operation !== 'post' ? this[config.restangularFields.etag] : null); + + if (_.isObject(callObj) && config.isRestangularized(callObj)) { + callObj = stripRestangular(callObj); } - }; - // Overriding HTTP Method - var callOperation = operation; - var callHeaders = _.extend({}, request.headers); - var isOverrideOperation = config.isOverridenMethod(operation); - if (isOverrideOperation) { - callOperation = 'post'; - callHeaders = _.extend(callHeaders, {'X-HTTP-Method-Override': operation === 'remove' ? 'DELETE' : operation.toUpperCase()}); - } else if (config.jsonp && callOperation === 'get') { - callOperation = 'jsonp'; - } + var request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl, + headers || {}, resParams || {}, this[config.restangularFields.httpConfig] || {}); + + var filledObject = {}; + filledObject = config.transformElem(filledObject, false, route, service); + + var okCallback = function(response) { + var resData = response.data; + var fullParams = response.config.params; + var elem = parseResponse(resData, operation, route, fetchUrl, response, deferred); + + // accept 0 as response + if (elem !== null && elem !== undefined && elem !== '') { + var data; + + if (true === config.plainByDefault) { + return resolvePromise(deferred, response, elem, filledObject); + } + + if (operation === 'post' && !__this[config.restangularFields.restangularCollection]) { + data = restangularizeElem( + __this[config.restangularFields.parentResource], + elem, + route, + true, + null, + fullParams + ); + resolvePromise(deferred, response, data, filledObject); + } else { + data = restangularizeElem( + __this[config.restangularFields.parentResource], + elem, + __this[config.restangularFields.route], + true, + null, + fullParams + ); + + data[config.restangularFields.singleOne] = __this[config.restangularFields.singleOne]; + resolvePromise(deferred, response, data, filledObject); + } + + } else { + resolvePromise(deferred, response, undefined, filledObject); + } + }; - if (config.isSafe(operation)) { + var errorCallback = function(response) { + if (response.status === 304 && config.isSafe(operation)) { + resolvePromise(deferred, response, __this, filledObject); + } else if (_.every(config.errorInterceptors, function(cb) { + return cb(response, deferred, okCallback) !== false; + })) { + // triggered if no callback returns false + deferred.reject(response); + } + }; + // Overriding HTTP Method + var callOperation = operation; + var callHeaders = _.extend({}, request.headers); + var isOverrideOperation = config.isOverridenMethod(operation); if (isOverrideOperation) { - urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params, - what, etag, callOperation)[callOperation]({}).then(okCallback, errorCallback); + callOperation = 'post'; + callHeaders = _.extend(callHeaders, { + 'X-HTTP-Method-Override': operation === 'remove' ? 'DELETE' : operation.toUpperCase() + }); + } else if (config.jsonp && callOperation === 'get') { + callOperation = 'jsonp'; + } + + if (config.isSafe(operation)) { + if (isOverrideOperation) { + urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params, + what, etag, callOperation)[callOperation]({}).then(okCallback, errorCallback); + } else { + urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params, + what, etag, callOperation)[callOperation]().then(okCallback, errorCallback); + } } else { urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params, - what, etag, callOperation)[callOperation]().then(okCallback, errorCallback); + what, etag, callOperation)[callOperation](request.element).then(okCallback, errorCallback); } - } else { - urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params, - what, etag, callOperation)[callOperation](request.element).then(okCallback, errorCallback); - } - - return restangularizePromise(deferred.promise, false, filledObject); - } - function getFunction(params, headers) { - return _.bind(elemFunction, this)('get', undefined, params, undefined, headers); - } + return restangularizePromise(deferred.promise, false, filledObject); + } - function deleteFunction(params, headers) { - return _.bind(elemFunction, this)('remove', undefined, params, undefined, headers); - } + function getFunction(params, headers) { + return _.bind(elemFunction, this)('get', undefined, params, undefined, headers); + } - function putFunction(params, headers) { - return _.bind(elemFunction, this)('put', undefined, params, undefined, headers); - } + function deleteFunction(params, headers) { + return _.bind(elemFunction, this)('remove', undefined, params, undefined, headers); + } - function postFunction(what, elem, params, headers) { - return _.bind(elemFunction, this)('post', what, params, elem, headers); - } + function putFunction(params, headers) { + return _.bind(elemFunction, this)('put', undefined, params, undefined, headers); + } - function headFunction(params, headers) { - return _.bind(elemFunction, this)('head', undefined, params, undefined, headers); - } + function postFunction(what, elem, params, headers) { + return _.bind(elemFunction, this)('post', what, params, elem, headers); + } - function traceFunction(params, headers) { - return _.bind(elemFunction, this)('trace', undefined, params, undefined, headers); - } + function headFunction(params, headers) { + return _.bind(elemFunction, this)('head', undefined, params, undefined, headers); + } - function optionsFunction(params, headers) { - return _.bind(elemFunction, this)('options', undefined, params, undefined, headers); - } + function traceFunction(params, headers) { + return _.bind(elemFunction, this)('trace', undefined, params, undefined, headers); + } - function patchFunction(elem, params, headers) { - return _.bind(elemFunction, this)('patch', undefined, params, elem, headers); - } + function optionsFunction(params, headers) { + return _.bind(elemFunction, this)('options', undefined, params, undefined, headers); + } - function customFunction(operation, path, params, headers, elem) { - return _.bind(elemFunction, this)(operation, path, params, elem, headers); - } + function patchFunction(elem, params, headers) { + return _.bind(elemFunction, this)('patch', undefined, params, elem, headers); + } - function addRestangularMethodFunction(name, operation, path, defaultParams, defaultHeaders, defaultElem) { - var bindedFunction; - if (operation === 'getList') { - bindedFunction = _.bind(fetchFunction, this, path); - } else { - bindedFunction = _.bind(customFunction, this, operation, path); + function customFunction(operation, path, params, headers, elem) { + return _.bind(elemFunction, this)(operation, path, params, elem, headers); } - var createdFunction = function(params, headers, elem) { - var callParams = _.defaults({ - params: params, - headers: headers, - elem: elem - }, { - params: defaultParams, - headers: defaultHeaders, - elem: defaultElem - }); - return bindedFunction(callParams.params, callParams.headers, callParams.elem); - }; + function addRestangularMethodFunction(name, operation, path, defaultParams, defaultHeaders, defaultElem) { + var bindedFunction; + if (operation === 'getList') { + bindedFunction = _.bind(fetchFunction, this, path); + } else { + bindedFunction = _.bind(customFunction, this, operation, path); + } - if (config.isSafe(operation)) { - this[name] = createdFunction; - } else { - this[name] = function(elem, params, headers) { - return createdFunction(params, headers, elem); + var createdFunction = function(params, headers, elem) { + var callParams = _.defaults({ + params: params, + headers: headers, + elem: elem + }, { + params: defaultParams, + headers: defaultHeaders, + elem: defaultElem + }); + return bindedFunction(callParams.params, callParams.headers, callParams.elem); }; + + if (config.isSafe(operation)) { + this[name] = createdFunction; + } else { + this[name] = function(elem, params, headers) { + return createdFunction(params, headers, elem); + }; + } } - } - function withConfigurationFunction(configurer) { - var newConfig = angular.copy(_.omit(config, 'configuration')); - Configurer.init(newConfig, newConfig); - configurer(newConfig); - return createServiceForConfiguration(newConfig); - } + function withConfigurationFunction(configurer) { + var newConfig = angular.copy(_.omit(config, 'configuration')); + Configurer.init(newConfig, newConfig); + configurer(newConfig); + return createServiceForConfiguration(newConfig); + } - function toService(route, parent) { - var knownCollectionMethods = _.values(config.restangularFields); - var serv = {}; - var collection = (parent || service).all(route); - serv.one = _.bind(one, (parent || service), parent, route); - serv.post = _.bind(collection.post, collection); - serv.getList = _.bind(collection.getList, collection); - serv.withHttpConfig = _.bind(collection.withHttpConfig, collection); - serv.get = _.bind(collection.get, collection); - - for (var prop in collection) { - if (collection.hasOwnProperty(prop) && _.isFunction(collection[prop]) && !_.includes(knownCollectionMethods, prop)) { - serv[prop] = _.bind(collection[prop], collection); + function toService(route, parent) { + var knownCollectionMethods = _.values(config.restangularFields); + var serv = {}; + var collection = (parent || service).all(route); + serv.one = _.bind(one, (parent || service), parent, route); + serv.post = _.bind(collection.post, collection); + serv.getList = _.bind(collection.getList, collection); + serv.withHttpConfig = _.bind(collection.withHttpConfig, collection); + serv.get = _.bind(collection.get, collection); + + for (var prop in collection) { + if (collection.hasOwnProperty(prop) && _.isFunction(collection[prop]) && !_.includes(knownCollectionMethods, prop)) { + serv[prop] = _.bind(collection[prop], collection); + } } - } - return serv; - } + return serv; + } - Configurer.init(service, config); + Configurer.init(service, config); - service.copy = _.bind(copyRestangularizedElement, service); + service.copy = _.bind(copyRestangularizedElement, service); - service.service = _.bind(toService, service); + service.service = _.bind(toService, service); - service.withConfig = _.bind(withConfigurationFunction, service); + service.withConfig = _.bind(withConfigurationFunction, service); - service.one = _.bind(one, service, null); + service.one = _.bind(one, service, null); - service.all = _.bind(all, service, null); + service.all = _.bind(all, service, null); - service.several = _.bind(several, service, null); + service.several = _.bind(several, service, null); - service.oneUrl = _.bind(oneUrl, service, null); + service.oneUrl = _.bind(oneUrl, service, null); - service.allUrl = _.bind(allUrl, service, null); + service.allUrl = _.bind(allUrl, service, null); - service.stripRestangular = _.bind(stripRestangular, service); + service.stripRestangular = _.bind(stripRestangular, service); - service.restangularizeElement = _.bind(restangularizeElem, service); + service.restangularizeElement = _.bind(restangularizeElem, service); - service.restangularizeCollection = _.bind(restangularizeCollectionAndElements, service); + service.restangularizeCollection = _.bind(restangularizeCollectionAndElements, service); - return service; - } + return service; + } - return createServiceForConfiguration(globalConfiguration); - }]; -}); + return createServiceForConfiguration(globalConfiguration); + }]; + }); return restangular.name; })); diff --git a/dist/restangular.min.js b/dist/restangular.min.js index 7e481e41..67d3cfc0 100644 --- a/dist/restangular.min.js +++ b/dist/restangular.min.js @@ -1,6 +1,6 @@ /** * Restful Resources service for AngularJS apps - * @version v1.6.0 - 2016-12-25 * @link https://github.com/mgonto/restangular + * @version v1.6.0 - 2017-01-05 * @link https://github.com/mgonto/restangular * @author Martin Gontovnikas * @license MIT License, http://www.opensource.org/licenses/MIT - */!function(a,b){"function"==typeof define&&define.amd?define(["lodash","angular"],b):"object"==typeof module&&module.exports?module.exports=b(require("lodash"),require("angular")):b(a._,a.angular)}(this,function(a,b){var c=b.module("restangular",[]);return c.provider("Restangular",function(){var c={};c.init=function(c,d){function e(b,c,d,e){var f={};return a.each(a.keys(e),function(g){var h=e[g];h.params=a.extend({},h.params,b.defaultRequestParams[h.method.toLowerCase()]),a.isEmpty(h.params)&&delete h.params,b.isSafe(h.method)?f[g]=function(){return c(a.extend(h,{url:d}))}:f[g]=function(b){return c(a.extend(h,{url:d,data:b}))}}),f}c.configuration=d;var f=["get","head","options","trace","getlist"];d.isSafe=function(b){return a.includes(f,b.toLowerCase())};var g=/^https?:\/\//i;d.isAbsoluteUrl=function(b){return a.isUndefined(d.absoluteUrl)||a.isNull(d.absoluteUrl)?b&&g.test(b):d.absoluteUrl},d.absoluteUrl=!!a.isUndefined(d.absoluteUrl)||d.absoluteUrl,c.setSelfLinkAbsoluteUrl=function(a){d.absoluteUrl=a},d.baseUrl=a.isUndefined(d.baseUrl)?"":d.baseUrl,c.setBaseUrl=function(a){return d.baseUrl=/\/$/.test(a)?a.substring(0,a.length-1):a,this},d.extraFields=d.extraFields||[],c.setExtraFields=function(a){return d.extraFields=a,this},d.defaultHttpFields=d.defaultHttpFields||{},c.setDefaultHttpFields=function(a){return d.defaultHttpFields=a,this},d.plainByDefault=d.plainByDefault||!1,c.setPlainByDefault=function(a){return d.plainByDefault=a===!0,this},d.withHttpValues=function(b,c){return a.defaults(c,b,d.defaultHttpFields)},d.encodeIds=!!a.isUndefined(d.encodeIds)||d.encodeIds,c.setEncodeIds=function(a){d.encodeIds=a},d.defaultRequestParams=d.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},c.setDefaultRequestParams=function(b,c){var e=[],f=c||b;return a.isUndefined(c)?e.push("common"):a.isArray(b)?e=b:e.push(b),a.each(e,function(a){d.defaultRequestParams[a]=f}),this},c.requestParams=d.defaultRequestParams,d.defaultHeaders=d.defaultHeaders||{},c.setDefaultHeaders=function(a){return d.defaultHeaders=a,c.defaultHeaders=d.defaultHeaders,this},c.defaultHeaders=d.defaultHeaders,d.methodOverriders=d.methodOverriders||[],c.setMethodOverriders=function(b){var c=a.extend([],b);return d.isOverridenMethod("delete",c)&&c.push("remove"),d.methodOverriders=c,this},d.jsonp=!a.isUndefined(d.jsonp)&&d.jsonp,c.setJsonp=function(a){d.jsonp=a},d.isOverridenMethod=function(b,c){var e=c||d.methodOverriders;return!a.isUndefined(a.find(e,function(a){return a.toLowerCase()===b.toLowerCase()}))},d.urlCreator=d.urlCreator||"path",c.setUrlCreator=function(b){if(!a.has(d.urlCreatorFactory,b))throw new Error("URL Path selected isn't valid");return d.urlCreator=b,this},d.restangularFields=d.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId",etag:"restangularEtag",selfLink:"href",get:"get",getList:"getList",put:"put",post:"post",remove:"remove",head:"head",trace:"trace",options:"options",patch:"patch",getRestangularUrl:"getRestangularUrl",getRequestedUrl:"getRequestedUrl",putElement:"putElement",addRestangularMethod:"addRestangularMethod",getParentList:"getParentList",clone:"clone",ids:"ids",httpConfig:"_$httpConfig",reqParams:"reqParams",one:"one",all:"all",several:"several",oneUrl:"oneUrl",allUrl:"allUrl",customPUT:"customPUT",customPATCH:"customPATCH",customPOST:"customPOST",customDELETE:"customDELETE",customGET:"customGET",customGETLIST:"customGETLIST",customOperation:"customOperation",doPUT:"doPUT",doPATCH:"doPATCH",doPOST:"doPOST",doDELETE:"doDELETE",doGET:"doGET",doGETLIST:"doGETLIST",fromServer:"fromServer",withConfig:"withConfig",withHttpConfig:"withHttpConfig",singleOne:"singleOne",plain:"plain",save:"save",restangularized:"restangularized"},c.setRestangularFields=function(b){return d.restangularFields=a.extend(d.restangularFields,b),this},d.isRestangularized=function(a){return!!a[d.restangularFields.restangularized]},d.setFieldToElem=function(b,c,d){var e=b.split("."),f=c;return a.each(a.initial(e),function(a){f[a]={},f=f[a]}),f[a.last(e)]=d,this},d.getFieldFromElem=function(c,d){var e=c.split("."),f=d;return a.each(e,function(a){f&&(f=f[a])}),b.copy(f)},d.setIdToElem=function(a,b){return d.setFieldToElem(d.restangularFields.id,a,b),this},d.getIdFromElem=function(a){return d.getFieldFromElem(d.restangularFields.id,a)},d.isValidId=function(b){return""!==b&&!a.isUndefined(b)&&!a.isNull(b)},d.setUrlToElem=function(a,b){return d.setFieldToElem(d.restangularFields.selfLink,a,b),this},d.getUrlFromElem=function(a){return d.getFieldFromElem(d.restangularFields.selfLink,a)},d.useCannonicalId=!a.isUndefined(d.useCannonicalId)&&d.useCannonicalId,c.setUseCannonicalId=function(a){return d.useCannonicalId=a,this},d.getCannonicalIdFromElem=function(a){var b=a[d.restangularFields.cannonicalId],c=d.isValidId(b)?b:d.getIdFromElem(a);return c},d.responseInterceptors=d.responseInterceptors||[],d.defaultResponseInterceptor=function(a){return a},d.responseExtractor=function(c,e,f,g,h,i){var j=b.copy(d.responseInterceptors);j.push(d.defaultResponseInterceptor);var k=c;return a.each(j,function(a){k=a(k,e,f,g,h,i)}),k},c.addResponseInterceptor=function(a){return d.responseInterceptors.push(a),this},d.errorInterceptors=d.errorInterceptors||[],c.addErrorInterceptor=function(a){return d.errorInterceptors.push(a),this},c.setResponseInterceptor=c.addResponseInterceptor,c.setResponseExtractor=c.addResponseInterceptor,c.setErrorInterceptor=c.addErrorInterceptor,d.requestInterceptors=d.requestInterceptors||[],d.defaultInterceptor=function(a,b,c,d,e,f,g){return{element:a,headers:e,params:f,httpConfig:g}},d.fullRequestInterceptor=function(c,e,f,g,h,i,j){var k=b.copy(d.requestInterceptors),l=d.defaultInterceptor(c,e,f,g,h,i,j);return a.reduce(k,function(b,c){return a.extend(b,c(b.element,e,f,g,b.headers,b.params,b.httpConfig))},l)},c.addRequestInterceptor=function(a){return d.requestInterceptors.push(function(b,c,d,e,f,g,h){return{headers:f,params:g,element:a(b,c,d,e),httpConfig:h}}),this},c.setRequestInterceptor=c.addRequestInterceptor,c.addFullRequestInterceptor=function(a){return d.requestInterceptors.push(a),this},c.setFullRequestInterceptor=c.addFullRequestInterceptor,d.onBeforeElemRestangularized=d.onBeforeElemRestangularized||function(a){return a},c.setOnBeforeElemRestangularized=function(a){return d.onBeforeElemRestangularized=a,this},c.setRestangularizePromiseInterceptor=function(a){return d.restangularizePromiseInterceptor=a,this},d.onElemRestangularized=d.onElemRestangularized||function(a){return a},c.setOnElemRestangularized=function(a){return d.onElemRestangularized=a,this},d.shouldSaveParent=d.shouldSaveParent||function(){return!0},c.setParentless=function(b){return a.isArray(b)?d.shouldSaveParent=function(c){return!a.includes(b,c)}:a.isBoolean(b)&&(d.shouldSaveParent=function(){return!b}),this},d.suffix=a.isUndefined(d.suffix)?null:d.suffix,c.setRequestSuffix=function(a){return d.suffix=a,this},d.transformers=d.transformers||{},d.matchTransformers=d.matchTransformers||[],c.addElementTransformer=function(b,e,f){var g=null,h=null;2===arguments.length?h=e:(h=f,g=e);var i=function(b,c){return a.isNull(g)||b===g?h(c):c};return a.isRegExp(b)?d.matchTransformers.push({regexp:b,transformer:i}):(d.transformers[b]||(d.transformers[b]=[]),d.transformers[b].push(i)),c},c.extendCollection=function(a,b){return c.addElementTransformer(a,!0,b)},c.extendModel=function(a,b){return c.addElementTransformer(a,!1,b)},d.transformElem=function(b,c,e,f,g){if(!g&&!d.transformLocalElements&&!b[d.restangularFields.fromServer])return b;var h=b,i=d.matchTransformers;i&&a.each(i,function(a){e.match(a.regexp)&&(h=a.transformer(c,h))});var j=d.transformers[e];return j&&a.each(j,function(a){h=a(c,h)}),d.onElemRestangularized(h,c,e,f)},d.transformLocalElements=!a.isUndefined(d.transformLocalElements)&&d.transformLocalElements,c.setTransformOnlyServerElements=function(a){d.transformLocalElements=!a},d.fullResponse=!a.isUndefined(d.fullResponse)&&d.fullResponse,c.setFullResponse=function(a){return d.fullResponse=a,this},d.urlCreatorFactory={};var h=function(){};h.prototype.setConfig=function(a){return this.config=a,this},h.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},h.prototype.resource=function(b,c,f,g,h,i,j,k){var l=a.defaults(h||{},this.config.defaultRequestParams.common),m=a.defaults(g||{},this.config.defaultHeaders);j&&(d.isSafe(k)?m["If-None-Match"]=j:m["If-Match"]=j);var n=this.base(b);if(i||0===i){var o="";/\/$/.test(n)||(o+="/"),o+=i,n+=o}return this.config.suffix&&n.indexOf(this.config.suffix,n.length-this.config.suffix.length)===-1&&!this.config.getUrlFromElem(b)&&(n+=this.config.suffix),b[this.config.restangularFields.httpConfig]=void 0,e(this.config,c,n,{getList:this.config.withHttpValues(f,{method:"GET",params:l,headers:m}),get:this.config.withHttpValues(f,{method:"GET",params:l,headers:m}),jsonp:this.config.withHttpValues(f,{method:"jsonp",params:l,headers:m}),put:this.config.withHttpValues(f,{method:"PUT",params:l,headers:m}),post:this.config.withHttpValues(f,{method:"POST",params:l,headers:m}),remove:this.config.withHttpValues(f,{method:"DELETE",params:l,headers:m}),head:this.config.withHttpValues(f,{method:"HEAD",params:l,headers:m}),trace:this.config.withHttpValues(f,{method:"TRACE",params:l,headers:m}),options:this.config.withHttpValues(f,{method:"OPTIONS",params:l,headers:m}),patch:this.config.withHttpValues(f,{method:"PATCH",params:l,headers:m})})};var i=function(){};i.prototype=new h,i.prototype.normalizeUrl=function(a){var b=/((?:http[s]?:)?\/\/)?(.*)?/.exec(a);return b[2]=b[2].replace(/[\\\/]+/g,"/"),"undefined"!=typeof b[1]?b[1]+b[2]:b[2]},i.prototype.base=function(b){var c=this;return a.reduce(this.parentsArray(b),function(a,b){var e,f=c.config.getUrlFromElem(b);if(f){if(c.config.isAbsoluteUrl(f))return f;e=f}else if(e=b[c.config.restangularFields.route],b[c.config.restangularFields.restangularCollection]){var g=b[c.config.restangularFields.ids];g&&(e+="/"+g.join(","))}else{var h;h=c.config.useCannonicalId?c.config.getCannonicalIdFromElem(b):c.config.getIdFromElem(b),d.isValidId(h)&&!b.singleOne&&(e+="/"+(c.config.encodeIds?encodeURIComponent(h):h))}return a=a.replace(/\/$/,"")+"/"+e,c.normalizeUrl(a)},this.config.baseUrl)},i.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},i.prototype.fetchRequestedUrl=function(a,c){function e(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b.sort()}function f(a,b,c){for(var d=e(a),f=0;f