angular-resource.js 27KB

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