2 * @license AngularJS v1.5.0
3 * (c) 2010-2016 Google, Inc. http://angularjs.org
6 (function(window, angular, undefined) {'use strict';
8 var $resourceMinErr = angular.$$minErr('$resource');
10 // Helper functions and regex to lookup a dotted path on an object
11 // stopping at undefined/null. The path must be composed of ASCII
12 // identifiers (just like $parse)
13 var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;
15 function isValidDottedPath(path) {
16 return (path != null && path !== '' && path !== 'hasOwnProperty' &&
17 MEMBER_NAME_REGEX.test('.' + path));
20 function lookupDottedPath(obj, path) {
21 if (!isValidDottedPath(path)) {
22 throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path);
24 var keys = path.split('.');
25 for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) {
27 obj = (obj !== null) ? obj[key] : undefined;
33 * Create a shallow copy of an object and clear other fields from the destination
35 function shallowClearAndCopy(src, dst) {
38 angular.forEach(dst, function(value, key) {
42 for (var key in src) {
43 if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
58 * The `ngResource` module provides interaction support with RESTful services
59 * via the $resource service.
62 * <div doc-module-components="ngResource"></div>
64 * See {@link ngResource.$resource `$resource`} for usage.
73 * @requires ng.$timeout
76 * A factory which creates a resource object that lets you interact with
77 * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
79 * The returned resource object has action methods which provide high-level behaviors without
80 * the need to interact with the low level {@link ng.$http $http} service.
82 * Requires the {@link ngResource `ngResource`} module to be installed.
84 * By default, trailing slashes will be stripped from the calculated URLs,
85 * which can pose problems with server backends that do not expect that
86 * behavior. This can be disabled by configuring the `$resourceProvider` like
90 app.config(['$resourceProvider', function($resourceProvider) {
91 // Don't strip trailing slashes from calculated URLs
92 $resourceProvider.defaults.stripTrailingSlashes = false;
96 * @param {string} url A parameterized URL template with parameters prefixed by `:` as in
97 * `/user/:username`. If you are using a URL with a port number (e.g.
98 * `http://example.com:8080/api`), it will be respected.
100 * If you are using a url with a suffix, just add the suffix, like this:
101 * `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`
102 * or even `$resource('http://example.com/resource/:resource_id.:format')`
103 * If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be
104 * collapsed down to a single `.`. If you need this sequence to appear and not collapse then you
105 * can escape it with `/\.`.
107 * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
108 * `actions` methods. If a parameter value is a function, it will be executed every time
109 * when a param value needs to be obtained for a request (unless the param was overridden).
111 * Each key value in the parameter object is first bound to url template if present and then any
112 * excess keys are appended to the url search query after the `?`.
114 * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
115 * URL `/path/greet?salutation=Hello`.
117 * If the parameter value is prefixed with `@` then the value for that parameter will be extracted
118 * from the corresponding property on the `data` object (provided when calling an action method).
119 * For example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of
120 * `someParam` will be `data.someProp`.
122 * @param {Object.<Object>=} actions Hash with declaration of custom actions that should extend
123 * the default set of resource actions. The declaration should be created in the format of {@link
124 * ng.$http#usage $http.config}:
126 * {action1: {method:?, params:?, isArray:?, headers:?, ...},
127 * action2: {method:?, params:?, isArray:?, headers:?, ...},
132 * - **`action`** – {string} – The name of action. This name becomes the name of the method on
133 * your resource object.
134 * - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,
135 * `DELETE`, `JSONP`, etc).
136 * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of
137 * the parameter value is a function, it will be executed every time when a param value needs to
138 * be obtained for a request (unless the param was overridden).
139 * - **`url`** – {string} – action specific `url` override. The url templating is supported just
140 * like for the resource-level urls.
141 * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,
142 * see `returns` section.
143 * - **`transformRequest`** –
144 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
145 * transform function or an array of such functions. The transform function takes the http
146 * request body and headers and returns its transformed (typically serialized) version.
147 * By default, transformRequest will contain one function that checks if the request data is
148 * an object and serializes to using `angular.toJson`. To prevent this behavior, set
149 * `transformRequest` to an empty array: `transformRequest: []`
150 * - **`transformResponse`** –
151 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
152 * transform function or an array of such functions. The transform function takes the http
153 * response body and headers and returns its transformed (typically deserialized) version.
154 * By default, transformResponse will contain one function that checks if the response looks
155 * like a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior,
156 * set `transformResponse` to an empty array: `transformResponse: []`
157 * - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
158 * GET request, otherwise if a cache instance built with
159 * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
161 * - **`timeout`** – `{number}` – timeout in milliseconds.<br />
162 * **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are
163 * **not** supported in $resource, because the same value would be used for multiple requests.
164 * If you are looking for a way to cancel requests, you should use the `cancellable` option.
165 * - **`cancellable`** – `{boolean}` – if set to true, the request made by a "non-instance" call
166 * will be cancelled (if not already completed) by calling `$cancelRequest()` on the call's
167 * return value. Calling `$cancelRequest()` for a non-cancellable or an already
168 * completed/cancelled request will have no effect.<br />
169 * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
171 * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)
172 * for more information.
173 * - **`responseType`** - `{string}` - see
174 * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
175 * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
176 * `response` and `responseError`. Both `response` and `responseError` interceptors get called
177 * with `http response` object. See {@link ng.$http $http interceptors}.
179 * @param {Object} options Hash with custom settings that should extend the
180 * default `$resourceProvider` behavior. The supported options are:
182 * - **`stripTrailingSlashes`** – {boolean} – If true then the trailing
183 * slashes from any calculated URL will be stripped. (Defaults to true.)
184 * - **`cancellable`** – {boolean} – If true, the request made by a "non-instance" call will be
185 * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return value.
186 * This can be overwritten per action. (Defaults to false.)
188 * @returns {Object} A resource "class" object with methods for the default set of resource actions
189 * optionally extended with custom `actions`. The default set contains these actions:
191 * { 'get': {method:'GET'},
192 * 'save': {method:'POST'},
193 * 'query': {method:'GET', isArray:true},
194 * 'remove': {method:'DELETE'},
195 * 'delete': {method:'DELETE'} };
198 * Calling these methods invoke an {@link ng.$http} with the specified http method,
199 * destination and parameters. When the data is returned from the server then the object is an
200 * instance of the resource class. The actions `save`, `remove` and `delete` are available on it
201 * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
202 * read, update, delete) on server-side data like this:
204 * var User = $resource('/user/:userId', {userId:'@id'});
205 * var user = User.get({userId:123}, function() {
211 * It is important to realize that invoking a $resource object method immediately returns an
212 * empty reference (object or array depending on `isArray`). Once the data is returned from the
213 * server the existing reference is populated with the actual data. This is a useful trick since
214 * usually the resource is assigned to a model which is then rendered by the view. Having an empty
215 * object results in no rendering, once the data arrives from the server then the object is
216 * populated with the data and the view automatically re-renders itself showing the new data. This
217 * means that in most cases one never has to write a callback function for the action methods.
219 * The action methods on the class object or instance object can be invoked with the following
222 * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
223 * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
224 * - non-GET instance actions: `instance.$action([parameters], [success], [error])`
227 * Success callback is called with (value, responseHeaders) arguments, where the value is
228 * the populated resource instance or collection object. The error callback is called
229 * with (httpResponse) argument.
231 * Class actions return empty instance (with additional properties below).
232 * Instance actions return promise of the action.
234 * The Resource instances and collections have these additional properties:
236 * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
237 * instance or collection.
239 * On success, the promise is resolved with the same resource instance or collection object,
240 * updated with data from server. This makes it easy to use in
241 * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
242 * rendering until the resource(s) are loaded.
244 * On failure, the promise is rejected with the {@link ng.$http http response} object, without
245 * the `resource` property.
247 * If an interceptor object was provided, the promise will instead be resolved with the value
248 * returned by the interceptor.
250 * - `$resolved`: `true` after first server interaction is completed (either with success or
251 * rejection), `false` before that. Knowing if the Resource has been resolved is useful in
254 * The Resource instances and collections have these additional methods:
256 * - `$cancelRequest`: If there is a cancellable, pending request related to the instance or
257 * collection, calling this method will abort the request.
261 * # Credit card resource
264 // Define CreditCard class
265 var CreditCard = $resource('/user/:userId/card/:cardId',
266 {userId:123, cardId:'@id'}, {
267 charge: {method:'POST', params:{charge:true}}
270 // We can retrieve a collection from the server
271 var cards = CreditCard.query(function() {
272 // GET: /user/123/card
273 // server returns: [ {id:456, number:'1234', name:'Smith'} ];
276 // each item is an instance of CreditCard
277 expect(card instanceof CreditCard).toEqual(true);
278 card.name = "J. Smith";
279 // non GET methods are mapped onto the instances
281 // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
282 // server returns: {id:456, number:'1234', name: 'J. Smith'};
284 // our custom method is mapped as well.
285 card.$charge({amount:9.99});
286 // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
289 // we can create an instance as well
290 var newCard = new CreditCard({number:'0123'});
291 newCard.name = "Mike Smith";
293 // POST: /user/123/card {number:'0123', name:'Mike Smith'}
294 // server returns: {id:789, number:'0123', name: 'Mike Smith'};
295 expect(newCard.id).toEqual(789);
298 * The object returned from this function execution is a resource "class" which has "static" method
299 * for each action in the definition.
301 * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
308 * When the data is returned from the server then the object is an instance of the resource type and
309 * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
310 * operations (create, read, update, delete) on server-side data.
313 var User = $resource('/user/:userId', {userId:'@id'});
314 User.get({userId:123}, function(user) {
320 * It's worth noting that the success callback for `get`, `query` and other methods gets passed
321 * in the response that came from the server as well as $http header getter function, so one
322 * could rewrite the above example and get access to http headers as:
325 var User = $resource('/user/:userId', {userId:'@id'});
326 User.get({userId:123}, function(user, getResponseHeaders){
328 user.$save(function(user, putResponseHeaders) {
329 //user => saved user object
330 //putResponseHeaders => $http header getter
335 * You can also access the raw `$http` promise via the `$promise` property on the object returned
338 var User = $resource('/user/:userId', {userId:'@id'});
339 User.get({userId:123})
340 .$promise.then(function(user) {
347 * # Creating a custom 'PUT' request
349 * In this example we create a custom method on our resource to make a PUT request
351 * var app = angular.module('app', ['ngResource', 'ngRoute']);
353 * // Some APIs expect a PUT request in the format URL/object/ID
354 * // Here we are creating an 'update' method
355 * app.factory('Notes', ['$resource', function($resource) {
356 * return $resource('/notes/:id', null,
358 * 'update': { method:'PUT' }
362 * // In our controller we get the ID from the URL using ngRoute and $routeParams
363 * // We pass in $routeParams and our Notes factory along with $scope
364 * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
365 function($scope, $routeParams, Notes) {
366 * // First get a note object from the factory
367 * var note = Notes.get({ id:$routeParams.id });
370 * // Now call update passing in the ID first then the object you are updating
371 * Notes.update({ id:$id }, note);
373 * // This will PUT /notes/ID with the note object in the request payload
379 * # Cancelling requests
381 * If an action's configuration specifies that it is cancellable, you can cancel the request related
382 * to an instance or collection (as long as it is a result of a "non-instance" call):
385 // ...defining the `Hotel` resource...
386 var Hotel = $resource('/api/hotel/:id', {id: '@id'}, {
387 // Let's make the `query()` method cancellable
388 query: {method: 'get', isArray: true, cancellable: true}
391 // ...somewhere in the PlanVacationController...
393 this.onDestinationChanged = function onDestinationChanged(destination) {
394 // We don't care about any pending request for hotels
395 // in a different destination any more
396 this.availableHotels.$cancelRequest();
398 // Let's query for hotels in '<destination>'
399 // (calls: /api/hotel?location=<destination>)
400 this.availableHotels = Hotel.query({location: destination});
405 angular.module('ngResource', ['ng']).
406 provider('$resource', function() {
407 var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^\/]*/;
411 // Strip slashes by default
412 stripTrailingSlashes: true,
414 // Default actions configuration
416 'get': {method: 'GET'},
417 'save': {method: 'POST'},
418 'query': {method: 'GET', isArray: true},
419 'remove': {method: 'DELETE'},
420 'delete': {method: 'DELETE'}
424 this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) {
426 var noop = angular.noop,
427 forEach = angular.forEach,
428 extend = angular.extend,
430 isFunction = angular.isFunction;
433 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
434 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set
435 * (pchar) allowed in path segments:
437 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
438 * pct-encoded = "%" HEXDIG HEXDIG
439 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
440 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
441 * / "*" / "+" / "," / ";" / "="
443 function encodeUriSegment(val) {
444 return encodeUriQuery(val, true).
445 replace(/%26/gi, '&').
446 replace(/%3D/gi, '=').
447 replace(/%2B/gi, '+');
452 * This method is intended for encoding *key* or *value* parts of query component. We need a
453 * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't
454 * have to be encoded per http://tools.ietf.org/html/rfc3986:
455 * query = *( pchar / "/" / "?" )
456 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
457 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
458 * pct-encoded = "%" HEXDIG HEXDIG
459 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
460 * / "*" / "+" / "," / ";" / "="
462 function encodeUriQuery(val, pctEncodeSpaces) {
463 return encodeURIComponent(val).
464 replace(/%40/gi, '@').
465 replace(/%3A/gi, ':').
466 replace(/%24/g, '$').
467 replace(/%2C/gi, ',').
468 replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
471 function Route(template, defaults) {
472 this.template = template;
473 this.defaults = extend({}, provider.defaults, defaults);
478 setUrlParams: function(config, params, actionUrl) {
480 url = actionUrl || self.template,
483 protocolAndDomain = '';
485 var urlParams = self.urlParams = {};
486 forEach(url.split(/\W/), function(param) {
487 if (param === 'hasOwnProperty') {
488 throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name.");
490 if (!(new RegExp("^\\d+$").test(param)) && param &&
491 (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) {
493 isQueryParamValue: (new RegExp("\\?.*=:" + param + "(?:\\W|$)")).test(url)
497 url = url.replace(/\\:/g, ':');
498 url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) {
499 protocolAndDomain = match;
503 params = params || {};
504 forEach(self.urlParams, function(paramInfo, urlParam) {
505 val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
506 if (angular.isDefined(val) && val !== null) {
507 if (paramInfo.isQueryParamValue) {
508 encodedVal = encodeUriQuery(val, true);
510 encodedVal = encodeUriSegment(val);
512 url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) {
513 return encodedVal + p1;
516 url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match,
517 leadingSlashes, tail) {
518 if (tail.charAt(0) == '/') {
521 return leadingSlashes + tail;
527 // strip trailing slashes and set the url (unless this behavior is specifically disabled)
528 if (self.defaults.stripTrailingSlashes) {
529 url = url.replace(/\/+$/, '') || '/';
532 // then replace collapse `/.` if found in the last URL path segment before the query
533 // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
534 url = url.replace(/\/\.(?=\w+($|\?))/, '.');
535 // replace escaped `/\.` with `/.`
536 config.url = protocolAndDomain + url.replace(/\/\\\./, '/.');
539 // set params - delegate param encoding to $http
540 forEach(params, function(value, key) {
541 if (!self.urlParams[key]) {
542 config.params = config.params || {};
543 config.params[key] = value;
550 function resourceFactory(url, paramDefaults, actions, options) {
551 var route = new Route(url, options);
553 actions = extend({}, provider.defaults.actions, actions);
555 function extractParams(data, actionParams) {
557 actionParams = extend({}, paramDefaults, actionParams);
558 forEach(actionParams, function(value, key) {
559 if (isFunction(value)) { value = value(); }
560 ids[key] = value && value.charAt && value.charAt(0) == '@' ?
561 lookupDottedPath(data, value.substr(1)) : value;
566 function defaultResponseInterceptor(response) {
567 return response.resource;
570 function Resource(value) {
571 shallowClearAndCopy(value || {}, this);
574 Resource.prototype.toJSON = function() {
575 var data = extend({}, this);
576 delete data.$promise;
577 delete data.$resolved;
581 forEach(actions, function(action, name) {
582 var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);
583 var numericTimeout = action.timeout;
584 var cancellable = angular.isDefined(action.cancellable) ? action.cancellable :
585 (options && angular.isDefined(options.cancellable)) ? options.cancellable :
586 provider.defaults.cancellable;
588 if (numericTimeout && !angular.isNumber(numericTimeout)) {
589 $log.debug('ngResource:\n' +
590 ' Only numeric values are allowed as `timeout`.\n' +
591 ' Promises are not supported in $resource, because the same value would ' +
592 'be used for multiple requests. If you are looking for a way to cancel ' +
593 'requests, you should use the `cancellable` option.');
594 delete action.timeout;
595 numericTimeout = null;
598 Resource[name] = function(a1, a2, a3, a4) {
599 var params = {}, data, success, error;
601 /* jshint -W086 */ /* (purposefully fall through case statements) */
602 switch (arguments.length) {
609 if (isFunction(a2)) {
610 if (isFunction(a1)) {
626 if (isFunction(a1)) success = a1;
627 else if (hasBody) data = a1;
632 throw $resourceMinErr('badargs',
633 "Expected up to 4 arguments [params, data, success, error], got {0} arguments",
636 /* jshint +W086 */ /* (purposefully fall through case statements) */
638 var isInstanceCall = this instanceof Resource;
639 var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
641 var responseInterceptor = action.interceptor && action.interceptor.response ||
642 defaultResponseInterceptor;
643 var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
646 var numericTimeoutPromise;
648 forEach(action, function(value, key) {
651 httpConfig[key] = copy(value);
661 if (!isInstanceCall && cancellable) {
662 timeoutDeferred = $q.defer();
663 httpConfig.timeout = timeoutDeferred.promise;
665 if (numericTimeout) {
666 numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout);
670 if (hasBody) httpConfig.data = data;
671 route.setUrlParams(httpConfig,
672 extend({}, extractParams(data, action.params || {}), params),
675 var promise = $http(httpConfig).then(function(response) {
676 var data = response.data;
679 // Need to convert action.isArray to boolean in case it is undefined
681 if (angular.isArray(data) !== (!!action.isArray)) {
682 throw $resourceMinErr('badcfg',
683 'Error in resource configuration for action `{0}`. Expected response to ' +
684 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',
685 angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);
688 if (action.isArray) {
690 forEach(data, function(item) {
691 if (typeof item === "object") {
692 value.push(new Resource(item));
694 // Valid JSON values may be string literals, and these should not be converted
695 // into objects. These items will not have access to the Resource prototype
696 // methods, but unfortunately there
701 var promise = value.$promise; // Save the promise
702 shallowClearAndCopy(data, value);
703 value.$promise = promise; // Restore the promise
706 response.resource = value;
709 }, function(response) {
710 (error || noop)(response);
711 return $q.reject(response);
714 promise.finally(function() {
715 value.$resolved = true;
716 if (!isInstanceCall && cancellable) {
717 value.$cancelRequest = angular.noop;
718 $timeout.cancel(numericTimeoutPromise);
719 timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null;
723 promise = promise.then(
725 var value = responseInterceptor(response);
726 (success || noop)(value, response.headers);
729 responseErrorInterceptor);
731 if (!isInstanceCall) {
732 // we are creating instance / collection
733 // - set the initial promise
734 // - return the instance / collection
735 value.$promise = promise;
736 value.$resolved = false;
737 if (cancellable) value.$cancelRequest = timeoutDeferred.resolve;
747 Resource.prototype['$' + name] = function(params, success, error) {
748 if (isFunction(params)) {
749 error = success; success = params; params = {};
751 var result = Resource[name].call(this, params, this, success, error);
752 return result.$promise || result;
756 Resource.bind = function(additionalParamDefaults) {
757 return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
763 return resourceFactory;
768 })(window, window.angular);