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