blob: e8bb301465c15fca342b390da5877c3e79a7eaaf [file] [log] [blame]
Ed Tanous904063f2017-03-02 16:48:24 -08001/**
2 * @license AngularJS v1.5.8
3 * (c) 2010-2016 Google, Inc. http://angularjs.org
4 * License: MIT
5 */
6(function(window, angular) {'use strict';
7
8var $resourceMinErr = angular.$$minErr('$resource');
9
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)
13var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;
14
15function isValidDottedPath(path) {
16 return (path != null && path !== '' && path !== 'hasOwnProperty' &&
17 MEMBER_NAME_REGEX.test('.' + path));
18}
19
20function lookupDottedPath(obj, path) {
21 if (!isValidDottedPath(path)) {
22 throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path);
23 }
24 var keys = path.split('.');
25 for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) {
26 var key = keys[i];
27 obj = (obj !== null) ? obj[key] : undefined;
28 }
29 return obj;
30}
31
32/**
33 * Create a shallow copy of an object and clear other fields from the destination
34 */
35function shallowClearAndCopy(src, dst) {
36 dst = dst || {};
37
38 angular.forEach(dst, function(value, key) {
39 delete dst[key];
40 });
41
42 for (var key in src) {
43 if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
44 dst[key] = src[key];
45 }
46 }
47
48 return dst;
49}
50
51/**
52 * @ngdoc module
53 * @name ngResource
54 * @description
55 *
56 * # ngResource
57 *
58 * The `ngResource` module provides interaction support with RESTful services
59 * via the $resource service.
60 *
61 *
62 * <div doc-module-components="ngResource"></div>
63 *
64 * See {@link ngResource.$resourceProvider} and {@link ngResource.$resource} for usage.
65 */
66
67/**
68 * @ngdoc provider
69 * @name $resourceProvider
70 *
71 * @description
72 *
73 * Use `$resourceProvider` to change the default behavior of the {@link ngResource.$resource}
74 * service.
75 *
76 * ## Dependencies
77 * Requires the {@link ngResource } module to be installed.
78 *
79 */
80
81/**
82 * @ngdoc service
83 * @name $resource
84 * @requires $http
85 * @requires ng.$log
86 * @requires $q
87 * @requires ng.$timeout
88 *
89 * @description
90 * A factory which creates a resource object that lets you interact with
91 * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
92 *
93 * The returned resource object has action methods which provide high-level behaviors without
94 * the need to interact with the low level {@link ng.$http $http} service.
95 *
96 * Requires the {@link ngResource `ngResource`} module to be installed.
97 *
98 * By default, trailing slashes will be stripped from the calculated URLs,
99 * which can pose problems with server backends that do not expect that
100 * behavior. This can be disabled by configuring the `$resourceProvider` like
101 * this:
102 *
103 * ```js
104 app.config(['$resourceProvider', function($resourceProvider) {
105 // Don't strip trailing slashes from calculated URLs
106 $resourceProvider.defaults.stripTrailingSlashes = false;
107 }]);
108 * ```
109 *
110 * @param {string} url A parameterized URL template with parameters prefixed by `:` as in
111 * `/user/:username`. If you are using a URL with a port number (e.g.
112 * `http://example.com:8080/api`), it will be respected.
113 *
114 * If you are using a url with a suffix, just add the suffix, like this:
115 * `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`
116 * or even `$resource('http://example.com/resource/:resource_id.:format')`
117 * If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be
118 * collapsed down to a single `.`. If you need this sequence to appear and not collapse then you
119 * can escape it with `/\.`.
120 *
121 * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
122 * `actions` methods. If a parameter value is a function, it will be called every time
123 * a param value needs to be obtained for a request (unless the param was overridden). The function
124 * will be passed the current data value as an argument.
125 *
126 * Each key value in the parameter object is first bound to url template if present and then any
127 * excess keys are appended to the url search query after the `?`.
128 *
129 * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
130 * URL `/path/greet?salutation=Hello`.
131 *
132 * If the parameter value is prefixed with `@`, then the value for that parameter will be
133 * extracted from the corresponding property on the `data` object (provided when calling a
134 * "non-GET" action method).
135 * For example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of
136 * `someParam` will be `data.someProp`.
137 * Note that the parameter will be ignored, when calling a "GET" action method (i.e. an action
138 * method that does not accept a request body)
139 *
140 * @param {Object.<Object>=} actions Hash with declaration of custom actions that should extend
141 * the default set of resource actions. The declaration should be created in the format of {@link
142 * ng.$http#usage $http.config}:
143 *
144 * {action1: {method:?, params:?, isArray:?, headers:?, ...},
145 * action2: {method:?, params:?, isArray:?, headers:?, ...},
146 * ...}
147 *
148 * Where:
149 *
150 * - **`action`** – {string} – The name of action. This name becomes the name of the method on
151 * your resource object.
152 * - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,
153 * `DELETE`, `JSONP`, etc).
154 * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of
155 * the parameter value is a function, it will be called every time when a param value needs to
156 * be obtained for a request (unless the param was overridden). The function will be passed the
157 * current data value as an argument.
158 * - **`url`** – {string} – action specific `url` override. The url templating is supported just
159 * like for the resource-level urls.
160 * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,
161 * see `returns` section.
162 * - **`transformRequest`** –
163 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
164 * transform function or an array of such functions. The transform function takes the http
165 * request body and headers and returns its transformed (typically serialized) version.
166 * By default, transformRequest will contain one function that checks if the request data is
167 * an object and serializes to using `angular.toJson`. To prevent this behavior, set
168 * `transformRequest` to an empty array: `transformRequest: []`
169 * - **`transformResponse`** –
170 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
171 * transform function or an array of such functions. The transform function takes the http
172 * response body and headers and returns its transformed (typically deserialized) version.
173 * By default, transformResponse will contain one function that checks if the response looks
174 * like a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior,
175 * set `transformResponse` to an empty array: `transformResponse: []`
176 * - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
177 * GET request, otherwise if a cache instance built with
178 * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
179 * caching.
180 * - **`timeout`** – `{number}` – timeout in milliseconds.<br />
181 * **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are
182 * **not** supported in $resource, because the same value would be used for multiple requests.
183 * If you are looking for a way to cancel requests, you should use the `cancellable` option.
184 * - **`cancellable`** – `{boolean}` – if set to true, the request made by a "non-instance" call
185 * will be cancelled (if not already completed) by calling `$cancelRequest()` on the call's
186 * return value. Calling `$cancelRequest()` for a non-cancellable or an already
187 * completed/cancelled request will have no effect.<br />
188 * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
189 * XHR object. See
190 * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)
191 * for more information.
192 * - **`responseType`** - `{string}` - see
193 * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
194 * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
195 * `response` and `responseError`. Both `response` and `responseError` interceptors get called
196 * with `http response` object. See {@link ng.$http $http interceptors}.
197 *
198 * @param {Object} options Hash with custom settings that should extend the
199 * default `$resourceProvider` behavior. The supported options are:
200 *
201 * - **`stripTrailingSlashes`** – {boolean} – If true then the trailing
202 * slashes from any calculated URL will be stripped. (Defaults to true.)
203 * - **`cancellable`** – {boolean} – If true, the request made by a "non-instance" call will be
204 * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return value.
205 * This can be overwritten per action. (Defaults to false.)
206 *
207 * @returns {Object} A resource "class" object with methods for the default set of resource actions
208 * optionally extended with custom `actions`. The default set contains these actions:
209 * ```js
210 * { 'get': {method:'GET'},
211 * 'save': {method:'POST'},
212 * 'query': {method:'GET', isArray:true},
213 * 'remove': {method:'DELETE'},
214 * 'delete': {method:'DELETE'} };
215 * ```
216 *
217 * Calling these methods invoke an {@link ng.$http} with the specified http method,
218 * destination and parameters. When the data is returned from the server then the object is an
219 * instance of the resource class. The actions `save`, `remove` and `delete` are available on it
220 * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
221 * read, update, delete) on server-side data like this:
222 * ```js
223 * var User = $resource('/user/:userId', {userId:'@id'});
224 * var user = User.get({userId:123}, function() {
225 * user.abc = true;
226 * user.$save();
227 * });
228 * ```
229 *
230 * It is important to realize that invoking a $resource object method immediately returns an
231 * empty reference (object or array depending on `isArray`). Once the data is returned from the
232 * server the existing reference is populated with the actual data. This is a useful trick since
233 * usually the resource is assigned to a model which is then rendered by the view. Having an empty
234 * object results in no rendering, once the data arrives from the server then the object is
235 * populated with the data and the view automatically re-renders itself showing the new data. This
236 * means that in most cases one never has to write a callback function for the action methods.
237 *
238 * The action methods on the class object or instance object can be invoked with the following
239 * parameters:
240 *
241 * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
242 * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
243 * - non-GET instance actions: `instance.$action([parameters], [success], [error])`
244 *
245 *
246 * Success callback is called with (value, responseHeaders) arguments, where the value is
247 * the populated resource instance or collection object. The error callback is called
248 * with (httpResponse) argument.
249 *
250 * Class actions return empty instance (with additional properties below).
251 * Instance actions return promise of the action.
252 *
253 * The Resource instances and collections have these additional properties:
254 *
255 * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
256 * instance or collection.
257 *
258 * On success, the promise is resolved with the same resource instance or collection object,
259 * updated with data from server. This makes it easy to use in
260 * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
261 * rendering until the resource(s) are loaded.
262 *
263 * On failure, the promise is rejected with the {@link ng.$http http response} object, without
264 * the `resource` property.
265 *
266 * If an interceptor object was provided, the promise will instead be resolved with the value
267 * returned by the interceptor.
268 *
269 * - `$resolved`: `true` after first server interaction is completed (either with success or
270 * rejection), `false` before that. Knowing if the Resource has been resolved is useful in
271 * data-binding.
272 *
273 * The Resource instances and collections have these additional methods:
274 *
275 * - `$cancelRequest`: If there is a cancellable, pending request related to the instance or
276 * collection, calling this method will abort the request.
277 *
278 * The Resource instances have these additional methods:
279 *
280 * - `toJSON`: It returns a simple object without any of the extra properties added as part of
281 * the Resource API. This object can be serialized through {@link angular.toJson} safely
282 * without attaching Angular-specific fields. Notice that `JSON.stringify` (and
283 * `angular.toJson`) automatically use this method when serializing a Resource instance
284 * (see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior)).
285 *
286 * @example
287 *
288 * # Credit card resource
289 *
290 * ```js
291 // Define CreditCard class
292 var CreditCard = $resource('/user/:userId/card/:cardId',
293 {userId:123, cardId:'@id'}, {
294 charge: {method:'POST', params:{charge:true}}
295 });
296
297 // We can retrieve a collection from the server
298 var cards = CreditCard.query(function() {
299 // GET: /user/123/card
300 // server returns: [ {id:456, number:'1234', name:'Smith'} ];
301
302 var card = cards[0];
303 // each item is an instance of CreditCard
304 expect(card instanceof CreditCard).toEqual(true);
305 card.name = "J. Smith";
306 // non GET methods are mapped onto the instances
307 card.$save();
308 // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
309 // server returns: {id:456, number:'1234', name: 'J. Smith'};
310
311 // our custom method is mapped as well.
312 card.$charge({amount:9.99});
313 // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
314 });
315
316 // we can create an instance as well
317 var newCard = new CreditCard({number:'0123'});
318 newCard.name = "Mike Smith";
319 newCard.$save();
320 // POST: /user/123/card {number:'0123', name:'Mike Smith'}
321 // server returns: {id:789, number:'0123', name: 'Mike Smith'};
322 expect(newCard.id).toEqual(789);
323 * ```
324 *
325 * The object returned from this function execution is a resource "class" which has "static" method
326 * for each action in the definition.
327 *
328 * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
329 * `headers`.
330 *
331 * @example
332 *
333 * # User resource
334 *
335 * When the data is returned from the server then the object is an instance of the resource type and
336 * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
337 * operations (create, read, update, delete) on server-side data.
338
339 ```js
340 var User = $resource('/user/:userId', {userId:'@id'});
341 User.get({userId:123}, function(user) {
342 user.abc = true;
343 user.$save();
344 });
345 ```
346 *
347 * It's worth noting that the success callback for `get`, `query` and other methods gets passed
348 * in the response that came from the server as well as $http header getter function, so one
349 * could rewrite the above example and get access to http headers as:
350 *
351 ```js
352 var User = $resource('/user/:userId', {userId:'@id'});
353 User.get({userId:123}, function(user, getResponseHeaders){
354 user.abc = true;
355 user.$save(function(user, putResponseHeaders) {
356 //user => saved user object
357 //putResponseHeaders => $http header getter
358 });
359 });
360 ```
361 *
362 * You can also access the raw `$http` promise via the `$promise` property on the object returned
363 *
364 ```
365 var User = $resource('/user/:userId', {userId:'@id'});
366 User.get({userId:123})
367 .$promise.then(function(user) {
368 $scope.user = user;
369 });
370 ```
371 *
372 * @example
373 *
374 * # Creating a custom 'PUT' request
375 *
376 * In this example we create a custom method on our resource to make a PUT request
377 * ```js
378 * var app = angular.module('app', ['ngResource', 'ngRoute']);
379 *
380 * // Some APIs expect a PUT request in the format URL/object/ID
381 * // Here we are creating an 'update' method
382 * app.factory('Notes', ['$resource', function($resource) {
383 * return $resource('/notes/:id', null,
384 * {
385 * 'update': { method:'PUT' }
386 * });
387 * }]);
388 *
389 * // In our controller we get the ID from the URL using ngRoute and $routeParams
390 * // We pass in $routeParams and our Notes factory along with $scope
391 * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
392 function($scope, $routeParams, Notes) {
393 * // First get a note object from the factory
394 * var note = Notes.get({ id:$routeParams.id });
395 * $id = note.id;
396 *
397 * // Now call update passing in the ID first then the object you are updating
398 * Notes.update({ id:$id }, note);
399 *
400 * // This will PUT /notes/ID with the note object in the request payload
401 * }]);
402 * ```
403 *
404 * @example
405 *
406 * # Cancelling requests
407 *
408 * If an action's configuration specifies that it is cancellable, you can cancel the request related
409 * to an instance or collection (as long as it is a result of a "non-instance" call):
410 *
411 ```js
412 // ...defining the `Hotel` resource...
413 var Hotel = $resource('/api/hotel/:id', {id: '@id'}, {
414 // Let's make the `query()` method cancellable
415 query: {method: 'get', isArray: true, cancellable: true}
416 });
417
418 // ...somewhere in the PlanVacationController...
419 ...
420 this.onDestinationChanged = function onDestinationChanged(destination) {
421 // We don't care about any pending request for hotels
422 // in a different destination any more
423 this.availableHotels.$cancelRequest();
424
425 // Let's query for hotels in '<destination>'
426 // (calls: /api/hotel?location=<destination>)
427 this.availableHotels = Hotel.query({location: destination});
428 };
429 ```
430 *
431 */
432angular.module('ngResource', ['ng']).
433 provider('$resource', function() {
434 var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^\/]*/;
435 var provider = this;
436
437 /**
438 * @ngdoc property
439 * @name $resourceProvider#defaults
440 * @description
441 * Object containing default options used when creating `$resource` instances.
442 *
443 * The default values satisfy a wide range of usecases, but you may choose to overwrite any of
444 * them to further customize your instances. The available properties are:
445 *
446 * - **stripTrailingSlashes** – `{boolean}` – If true, then the trailing slashes from any
447 * calculated URL will be stripped.<br />
448 * (Defaults to true.)
449 * - **cancellable** – `{boolean}` – If true, the request made by a "non-instance" call will be
450 * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return
451 * value. For more details, see {@link ngResource.$resource}. This can be overwritten per
452 * resource class or action.<br />
453 * (Defaults to false.)
454 * - **actions** - `{Object.<Object>}` - A hash with default actions declarations. Actions are
455 * high-level methods corresponding to RESTful actions/methods on resources. An action may
456 * specify what HTTP method to use, what URL to hit, if the return value will be a single
457 * object or a collection (array) of objects etc. For more details, see
458 * {@link ngResource.$resource}. The actions can also be enhanced or overwritten per resource
459 * class.<br />
460 * The default actions are:
461 * ```js
462 * {
463 * get: {method: 'GET'},
464 * save: {method: 'POST'},
465 * query: {method: 'GET', isArray: true},
466 * remove: {method: 'DELETE'},
467 * delete: {method: 'DELETE'}
468 * }
469 * ```
470 *
471 * #### Example
472 *
473 * For example, you can specify a new `update` action that uses the `PUT` HTTP verb:
474 *
475 * ```js
476 * angular.
477 * module('myApp').
478 * config(['resourceProvider', function ($resourceProvider) {
479 * $resourceProvider.defaults.actions.update = {
480 * method: 'PUT'
481 * };
482 * });
483 * ```
484 *
485 * Or you can even overwrite the whole `actions` list and specify your own:
486 *
487 * ```js
488 * angular.
489 * module('myApp').
490 * config(['resourceProvider', function ($resourceProvider) {
491 * $resourceProvider.defaults.actions = {
492 * create: {method: 'POST'}
493 * get: {method: 'GET'},
494 * getAll: {method: 'GET', isArray:true},
495 * update: {method: 'PUT'},
496 * delete: {method: 'DELETE'}
497 * };
498 * });
499 * ```
500 *
501 */
502 this.defaults = {
503 // Strip slashes by default
504 stripTrailingSlashes: true,
505
506 // Make non-instance requests cancellable (via `$cancelRequest()`)
507 cancellable: false,
508
509 // Default actions configuration
510 actions: {
511 'get': {method: 'GET'},
512 'save': {method: 'POST'},
513 'query': {method: 'GET', isArray: true},
514 'remove': {method: 'DELETE'},
515 'delete': {method: 'DELETE'}
516 }
517 };
518
519 this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) {
520
521 var noop = angular.noop,
522 forEach = angular.forEach,
523 extend = angular.extend,
524 copy = angular.copy,
525 isFunction = angular.isFunction;
526
527 /**
528 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
529 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set
530 * (pchar) allowed in path segments:
531 * segment = *pchar
532 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
533 * pct-encoded = "%" HEXDIG HEXDIG
534 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
535 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
536 * / "*" / "+" / "," / ";" / "="
537 */
538 function encodeUriSegment(val) {
539 return encodeUriQuery(val, true).
540 replace(/%26/gi, '&').
541 replace(/%3D/gi, '=').
542 replace(/%2B/gi, '+');
543 }
544
545
546 /**
547 * This method is intended for encoding *key* or *value* parts of query component. We need a
548 * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't
549 * have to be encoded per http://tools.ietf.org/html/rfc3986:
550 * query = *( pchar / "/" / "?" )
551 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
552 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
553 * pct-encoded = "%" HEXDIG HEXDIG
554 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
555 * / "*" / "+" / "," / ";" / "="
556 */
557 function encodeUriQuery(val, pctEncodeSpaces) {
558 return encodeURIComponent(val).
559 replace(/%40/gi, '@').
560 replace(/%3A/gi, ':').
561 replace(/%24/g, '$').
562 replace(/%2C/gi, ',').
563 replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
564 }
565
566 function Route(template, defaults) {
567 this.template = template;
568 this.defaults = extend({}, provider.defaults, defaults);
569 this.urlParams = {};
570 }
571
572 Route.prototype = {
573 setUrlParams: function(config, params, actionUrl) {
574 var self = this,
575 url = actionUrl || self.template,
576 val,
577 encodedVal,
578 protocolAndDomain = '';
579
580 var urlParams = self.urlParams = {};
581 forEach(url.split(/\W/), function(param) {
582 if (param === 'hasOwnProperty') {
583 throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name.");
584 }
585 if (!(new RegExp("^\\d+$").test(param)) && param &&
586 (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) {
587 urlParams[param] = {
588 isQueryParamValue: (new RegExp("\\?.*=:" + param + "(?:\\W|$)")).test(url)
589 };
590 }
591 });
592 url = url.replace(/\\:/g, ':');
593 url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) {
594 protocolAndDomain = match;
595 return '';
596 });
597
598 params = params || {};
599 forEach(self.urlParams, function(paramInfo, urlParam) {
600 val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
601 if (angular.isDefined(val) && val !== null) {
602 if (paramInfo.isQueryParamValue) {
603 encodedVal = encodeUriQuery(val, true);
604 } else {
605 encodedVal = encodeUriSegment(val);
606 }
607 url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) {
608 return encodedVal + p1;
609 });
610 } else {
611 url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match,
612 leadingSlashes, tail) {
613 if (tail.charAt(0) == '/') {
614 return tail;
615 } else {
616 return leadingSlashes + tail;
617 }
618 });
619 }
620 });
621
622 // strip trailing slashes and set the url (unless this behavior is specifically disabled)
623 if (self.defaults.stripTrailingSlashes) {
624 url = url.replace(/\/+$/, '') || '/';
625 }
626
627 // then replace collapse `/.` if found in the last URL path segment before the query
628 // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
629 url = url.replace(/\/\.(?=\w+($|\?))/, '.');
630 // replace escaped `/\.` with `/.`
631 config.url = protocolAndDomain + url.replace(/\/\\\./, '/.');
632
633
634 // set params - delegate param encoding to $http
635 forEach(params, function(value, key) {
636 if (!self.urlParams[key]) {
637 config.params = config.params || {};
638 config.params[key] = value;
639 }
640 });
641 }
642 };
643
644
645 function resourceFactory(url, paramDefaults, actions, options) {
646 var route = new Route(url, options);
647
648 actions = extend({}, provider.defaults.actions, actions);
649
650 function extractParams(data, actionParams) {
651 var ids = {};
652 actionParams = extend({}, paramDefaults, actionParams);
653 forEach(actionParams, function(value, key) {
654 if (isFunction(value)) { value = value(data); }
655 ids[key] = value && value.charAt && value.charAt(0) == '@' ?
656 lookupDottedPath(data, value.substr(1)) : value;
657 });
658 return ids;
659 }
660
661 function defaultResponseInterceptor(response) {
662 return response.resource;
663 }
664
665 function Resource(value) {
666 shallowClearAndCopy(value || {}, this);
667 }
668
669 Resource.prototype.toJSON = function() {
670 var data = extend({}, this);
671 delete data.$promise;
672 delete data.$resolved;
673 return data;
674 };
675
676 forEach(actions, function(action, name) {
677 var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);
678 var numericTimeout = action.timeout;
679 var cancellable = angular.isDefined(action.cancellable) ? action.cancellable :
680 (options && angular.isDefined(options.cancellable)) ? options.cancellable :
681 provider.defaults.cancellable;
682
683 if (numericTimeout && !angular.isNumber(numericTimeout)) {
684 $log.debug('ngResource:\n' +
685 ' Only numeric values are allowed as `timeout`.\n' +
686 ' Promises are not supported in $resource, because the same value would ' +
687 'be used for multiple requests. If you are looking for a way to cancel ' +
688 'requests, you should use the `cancellable` option.');
689 delete action.timeout;
690 numericTimeout = null;
691 }
692
693 Resource[name] = function(a1, a2, a3, a4) {
694 var params = {}, data, success, error;
695
696 /* jshint -W086 */ /* (purposefully fall through case statements) */
697 switch (arguments.length) {
698 case 4:
699 error = a4;
700 success = a3;
701 //fallthrough
702 case 3:
703 case 2:
704 if (isFunction(a2)) {
705 if (isFunction(a1)) {
706 success = a1;
707 error = a2;
708 break;
709 }
710
711 success = a2;
712 error = a3;
713 //fallthrough
714 } else {
715 params = a1;
716 data = a2;
717 success = a3;
718 break;
719 }
720 case 1:
721 if (isFunction(a1)) success = a1;
722 else if (hasBody) data = a1;
723 else params = a1;
724 break;
725 case 0: break;
726 default:
727 throw $resourceMinErr('badargs',
728 "Expected up to 4 arguments [params, data, success, error], got {0} arguments",
729 arguments.length);
730 }
731 /* jshint +W086 */ /* (purposefully fall through case statements) */
732
733 var isInstanceCall = this instanceof Resource;
734 var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
735 var httpConfig = {};
736 var responseInterceptor = action.interceptor && action.interceptor.response ||
737 defaultResponseInterceptor;
738 var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
739 undefined;
740 var timeoutDeferred;
741 var numericTimeoutPromise;
742
743 forEach(action, function(value, key) {
744 switch (key) {
745 default:
746 httpConfig[key] = copy(value);
747 break;
748 case 'params':
749 case 'isArray':
750 case 'interceptor':
751 case 'cancellable':
752 break;
753 }
754 });
755
756 if (!isInstanceCall && cancellable) {
757 timeoutDeferred = $q.defer();
758 httpConfig.timeout = timeoutDeferred.promise;
759
760 if (numericTimeout) {
761 numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout);
762 }
763 }
764
765 if (hasBody) httpConfig.data = data;
766 route.setUrlParams(httpConfig,
767 extend({}, extractParams(data, action.params || {}), params),
768 action.url);
769
770 var promise = $http(httpConfig).then(function(response) {
771 var data = response.data;
772
773 if (data) {
774 // Need to convert action.isArray to boolean in case it is undefined
775 // jshint -W018
776 if (angular.isArray(data) !== (!!action.isArray)) {
777 throw $resourceMinErr('badcfg',
778 'Error in resource configuration for action `{0}`. Expected response to ' +
779 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',
780 angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);
781 }
782 // jshint +W018
783 if (action.isArray) {
784 value.length = 0;
785 forEach(data, function(item) {
786 if (typeof item === "object") {
787 value.push(new Resource(item));
788 } else {
789 // Valid JSON values may be string literals, and these should not be converted
790 // into objects. These items will not have access to the Resource prototype
791 // methods, but unfortunately there
792 value.push(item);
793 }
794 });
795 } else {
796 var promise = value.$promise; // Save the promise
797 shallowClearAndCopy(data, value);
798 value.$promise = promise; // Restore the promise
799 }
800 }
801 response.resource = value;
802
803 return response;
804 }, function(response) {
805 (error || noop)(response);
806 return $q.reject(response);
807 });
808
809 promise['finally'](function() {
810 value.$resolved = true;
811 if (!isInstanceCall && cancellable) {
812 value.$cancelRequest = angular.noop;
813 $timeout.cancel(numericTimeoutPromise);
814 timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null;
815 }
816 });
817
818 promise = promise.then(
819 function(response) {
820 var value = responseInterceptor(response);
821 (success || noop)(value, response.headers);
822 return value;
823 },
824 responseErrorInterceptor);
825
826 if (!isInstanceCall) {
827 // we are creating instance / collection
828 // - set the initial promise
829 // - return the instance / collection
830 value.$promise = promise;
831 value.$resolved = false;
832 if (cancellable) value.$cancelRequest = timeoutDeferred.resolve;
833
834 return value;
835 }
836
837 // instance call
838 return promise;
839 };
840
841
842 Resource.prototype['$' + name] = function(params, success, error) {
843 if (isFunction(params)) {
844 error = success; success = params; params = {};
845 }
846 var result = Resource[name].call(this, params, this, success, error);
847 return result.$promise || result;
848 };
849 });
850
851 Resource.bind = function(additionalParamDefaults) {
852 return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
853 };
854
855 return Resource;
856 }
857
858 return resourceFactory;
859 }];
860 });
861
862
863})(window, window.angular);