angular-resource.js 34 KB

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