angular-resource.js 40 KB

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