Nav apraksta

angular-resource.js 34KB

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