angular-resource.js 31 KB

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