angular-resource.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. /**
  2. * @license AngularJS v1.3.15
  3. * (c) 2010-2014 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 && obj !== undefined; 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 parametrized 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. Error callback is called
  208. * with (httpResponse) argument.
  209. *
  210. * Class actions return empty instance (with additional properties below).
  211. * Instance actions return promise of the action.
  212. *
  213. * The Resource instances and collection have these additional properties:
  214. *
  215. * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
  216. * instance or collection.
  217. *
  218. * On success, the promise is resolved with the same resource instance or collection object,
  219. * updated with data from server. This makes it easy to use in
  220. * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
  221. * rendering until the resource(s) are loaded.
  222. *
  223. * On failure, the promise is resolved with the {@link ng.$http http response} object, without
  224. * the `resource` property.
  225. *
  226. * If an interceptor object was provided, the promise will instead be resolved with the value
  227. * returned by the interceptor.
  228. *
  229. * - `$resolved`: `true` after first server interaction is completed (either with success or
  230. * rejection), `false` before that. Knowing if the Resource has been resolved is useful in
  231. * data-binding.
  232. *
  233. * @example
  234. *
  235. * # Credit card resource
  236. *
  237. * ```js
  238. // Define CreditCard class
  239. var CreditCard = $resource('/user/:userId/card/:cardId',
  240. {userId:123, cardId:'@id'}, {
  241. charge: {method:'POST', params:{charge:true}}
  242. });
  243. // We can retrieve a collection from the server
  244. var cards = CreditCard.query(function() {
  245. // GET: /user/123/card
  246. // server returns: [ {id:456, number:'1234', name:'Smith'} ];
  247. var card = cards[0];
  248. // each item is an instance of CreditCard
  249. expect(card instanceof CreditCard).toEqual(true);
  250. card.name = "J. Smith";
  251. // non GET methods are mapped onto the instances
  252. card.$save();
  253. // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
  254. // server returns: {id:456, number:'1234', name: 'J. Smith'};
  255. // our custom method is mapped as well.
  256. card.$charge({amount:9.99});
  257. // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
  258. });
  259. // we can create an instance as well
  260. var newCard = new CreditCard({number:'0123'});
  261. newCard.name = "Mike Smith";
  262. newCard.$save();
  263. // POST: /user/123/card {number:'0123', name:'Mike Smith'}
  264. // server returns: {id:789, number:'0123', name: 'Mike Smith'};
  265. expect(newCard.id).toEqual(789);
  266. * ```
  267. *
  268. * The object returned from this function execution is a resource "class" which has "static" method
  269. * for each action in the definition.
  270. *
  271. * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
  272. * `headers`.
  273. * When the data is returned from the server then the object is an instance of the resource type and
  274. * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
  275. * operations (create, read, update, delete) on server-side data.
  276. ```js
  277. var User = $resource('/user/:userId', {userId:'@id'});
  278. User.get({userId:123}, function(user) {
  279. user.abc = true;
  280. user.$save();
  281. });
  282. ```
  283. *
  284. * It's worth noting that the success callback for `get`, `query` and other methods gets passed
  285. * in the response that came from the server as well as $http header getter function, so one
  286. * could rewrite the above example and get access to http headers as:
  287. *
  288. ```js
  289. var User = $resource('/user/:userId', {userId:'@id'});
  290. User.get({userId:123}, function(u, getResponseHeaders){
  291. u.abc = true;
  292. u.$save(function(u, putResponseHeaders) {
  293. //u => saved user object
  294. //putResponseHeaders => $http header getter
  295. });
  296. });
  297. ```
  298. *
  299. * You can also access the raw `$http` promise via the `$promise` property on the object returned
  300. *
  301. ```
  302. var User = $resource('/user/:userId', {userId:'@id'});
  303. User.get({userId:123})
  304. .$promise.then(function(user) {
  305. $scope.user = user;
  306. });
  307. ```
  308. * # Creating a custom 'PUT' request
  309. * In this example we create a custom method on our resource to make a PUT request
  310. * ```js
  311. * var app = angular.module('app', ['ngResource', 'ngRoute']);
  312. *
  313. * // Some APIs expect a PUT request in the format URL/object/ID
  314. * // Here we are creating an 'update' method
  315. * app.factory('Notes', ['$resource', function($resource) {
  316. * return $resource('/notes/:id', null,
  317. * {
  318. * 'update': { method:'PUT' }
  319. * });
  320. * }]);
  321. *
  322. * // In our controller we get the ID from the URL using ngRoute and $routeParams
  323. * // We pass in $routeParams and our Notes factory along with $scope
  324. * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
  325. function($scope, $routeParams, Notes) {
  326. * // First get a note object from the factory
  327. * var note = Notes.get({ id:$routeParams.id });
  328. * $id = note.id;
  329. *
  330. * // Now call update passing in the ID first then the object you are updating
  331. * Notes.update({ id:$id }, note);
  332. *
  333. * // This will PUT /notes/ID with the note object in the request payload
  334. * }]);
  335. * ```
  336. */
  337. angular.module('ngResource', ['ng']).
  338. provider('$resource', function() {
  339. var provider = this;
  340. this.defaults = {
  341. // Strip slashes by default
  342. stripTrailingSlashes: true,
  343. // Default actions configuration
  344. actions: {
  345. 'get': {method: 'GET'},
  346. 'save': {method: 'POST'},
  347. 'query': {method: 'GET', isArray: true},
  348. 'remove': {method: 'DELETE'},
  349. 'delete': {method: 'DELETE'}
  350. }
  351. };
  352. this.$get = ['$http', '$q', function($http, $q) {
  353. var noop = angular.noop,
  354. forEach = angular.forEach,
  355. extend = angular.extend,
  356. copy = angular.copy,
  357. isFunction = angular.isFunction;
  358. /**
  359. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  360. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set
  361. * (pchar) allowed in path segments:
  362. * segment = *pchar
  363. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  364. * pct-encoded = "%" HEXDIG HEXDIG
  365. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  366. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  367. * / "*" / "+" / "," / ";" / "="
  368. */
  369. function encodeUriSegment(val) {
  370. return encodeUriQuery(val, true).
  371. replace(/%26/gi, '&').
  372. replace(/%3D/gi, '=').
  373. replace(/%2B/gi, '+');
  374. }
  375. /**
  376. * This method is intended for encoding *key* or *value* parts of query component. We need a
  377. * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't
  378. * have to be encoded per http://tools.ietf.org/html/rfc3986:
  379. * query = *( pchar / "/" / "?" )
  380. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  381. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  382. * pct-encoded = "%" HEXDIG HEXDIG
  383. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  384. * / "*" / "+" / "," / ";" / "="
  385. */
  386. function encodeUriQuery(val, pctEncodeSpaces) {
  387. return encodeURIComponent(val).
  388. replace(/%40/gi, '@').
  389. replace(/%3A/gi, ':').
  390. replace(/%24/g, '$').
  391. replace(/%2C/gi, ',').
  392. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  393. }
  394. function Route(template, defaults) {
  395. this.template = template;
  396. this.defaults = extend({}, provider.defaults, defaults);
  397. this.urlParams = {};
  398. }
  399. Route.prototype = {
  400. setUrlParams: function(config, params, actionUrl) {
  401. var self = this,
  402. url = actionUrl || self.template,
  403. val,
  404. encodedVal;
  405. var urlParams = self.urlParams = {};
  406. forEach(url.split(/\W/), function(param) {
  407. if (param === 'hasOwnProperty') {
  408. throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name.");
  409. }
  410. if (!(new RegExp("^\\d+$").test(param)) && param &&
  411. (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) {
  412. urlParams[param] = true;
  413. }
  414. });
  415. url = url.replace(/\\:/g, ':');
  416. params = params || {};
  417. forEach(self.urlParams, function(_, urlParam) {
  418. val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
  419. if (angular.isDefined(val) && val !== null) {
  420. encodedVal = encodeUriSegment(val);
  421. url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) {
  422. return encodedVal + p1;
  423. });
  424. } else {
  425. url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match,
  426. leadingSlashes, tail) {
  427. if (tail.charAt(0) == '/') {
  428. return tail;
  429. } else {
  430. return leadingSlashes + tail;
  431. }
  432. });
  433. }
  434. });
  435. // strip trailing slashes and set the url (unless this behavior is specifically disabled)
  436. if (self.defaults.stripTrailingSlashes) {
  437. url = url.replace(/\/+$/, '') || '/';
  438. }
  439. // then replace collapse `/.` if found in the last URL path segment before the query
  440. // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
  441. url = url.replace(/\/\.(?=\w+($|\?))/, '.');
  442. // replace escaped `/\.` with `/.`
  443. config.url = url.replace(/\/\\\./, '/.');
  444. // set params - delegate param encoding to $http
  445. forEach(params, function(value, key) {
  446. if (!self.urlParams[key]) {
  447. config.params = config.params || {};
  448. config.params[key] = value;
  449. }
  450. });
  451. }
  452. };
  453. function resourceFactory(url, paramDefaults, actions, options) {
  454. var route = new Route(url, options);
  455. actions = extend({}, provider.defaults.actions, actions);
  456. function extractParams(data, actionParams) {
  457. var ids = {};
  458. actionParams = extend({}, paramDefaults, actionParams);
  459. forEach(actionParams, function(value, key) {
  460. if (isFunction(value)) { value = value(); }
  461. ids[key] = value && value.charAt && value.charAt(0) == '@' ?
  462. lookupDottedPath(data, value.substr(1)) : value;
  463. });
  464. return ids;
  465. }
  466. function defaultResponseInterceptor(response) {
  467. return response.resource;
  468. }
  469. function Resource(value) {
  470. shallowClearAndCopy(value || {}, this);
  471. }
  472. Resource.prototype.toJSON = function() {
  473. var data = extend({}, this);
  474. delete data.$promise;
  475. delete data.$resolved;
  476. return data;
  477. };
  478. forEach(actions, function(action, name) {
  479. var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);
  480. Resource[name] = function(a1, a2, a3, a4) {
  481. var params = {}, data, success, error;
  482. /* jshint -W086 */ /* (purposefully fall through case statements) */
  483. switch (arguments.length) {
  484. case 4:
  485. error = a4;
  486. success = a3;
  487. //fallthrough
  488. case 3:
  489. case 2:
  490. if (isFunction(a2)) {
  491. if (isFunction(a1)) {
  492. success = a1;
  493. error = a2;
  494. break;
  495. }
  496. success = a2;
  497. error = a3;
  498. //fallthrough
  499. } else {
  500. params = a1;
  501. data = a2;
  502. success = a3;
  503. break;
  504. }
  505. case 1:
  506. if (isFunction(a1)) success = a1;
  507. else if (hasBody) data = a1;
  508. else params = a1;
  509. break;
  510. case 0: break;
  511. default:
  512. throw $resourceMinErr('badargs',
  513. "Expected up to 4 arguments [params, data, success, error], got {0} arguments",
  514. arguments.length);
  515. }
  516. /* jshint +W086 */ /* (purposefully fall through case statements) */
  517. var isInstanceCall = this instanceof Resource;
  518. var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
  519. var httpConfig = {};
  520. var responseInterceptor = action.interceptor && action.interceptor.response ||
  521. defaultResponseInterceptor;
  522. var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
  523. undefined;
  524. forEach(action, function(value, key) {
  525. if (key != 'params' && key != 'isArray' && key != 'interceptor') {
  526. httpConfig[key] = copy(value);
  527. }
  528. });
  529. if (hasBody) httpConfig.data = data;
  530. route.setUrlParams(httpConfig,
  531. extend({}, extractParams(data, action.params || {}), params),
  532. action.url);
  533. var promise = $http(httpConfig).then(function(response) {
  534. var data = response.data,
  535. promise = value.$promise;
  536. if (data) {
  537. // Need to convert action.isArray to boolean in case it is undefined
  538. // jshint -W018
  539. if (angular.isArray(data) !== (!!action.isArray)) {
  540. throw $resourceMinErr('badcfg',
  541. 'Error in resource configuration for action `{0}`. Expected response to ' +
  542. 'contain an {1} but got an {2}', name, action.isArray ? 'array' : 'object',
  543. angular.isArray(data) ? 'array' : 'object');
  544. }
  545. // jshint +W018
  546. if (action.isArray) {
  547. value.length = 0;
  548. forEach(data, function(item) {
  549. if (typeof item === "object") {
  550. value.push(new Resource(item));
  551. } else {
  552. // Valid JSON values may be string literals, and these should not be converted
  553. // into objects. These items will not have access to the Resource prototype
  554. // methods, but unfortunately there
  555. value.push(item);
  556. }
  557. });
  558. } else {
  559. shallowClearAndCopy(data, value);
  560. value.$promise = promise;
  561. }
  562. }
  563. value.$resolved = true;
  564. response.resource = value;
  565. return response;
  566. }, function(response) {
  567. value.$resolved = true;
  568. (error || noop)(response);
  569. return $q.reject(response);
  570. });
  571. promise = promise.then(
  572. function(response) {
  573. var value = responseInterceptor(response);
  574. (success || noop)(value, response.headers);
  575. return value;
  576. },
  577. responseErrorInterceptor);
  578. if (!isInstanceCall) {
  579. // we are creating instance / collection
  580. // - set the initial promise
  581. // - return the instance / collection
  582. value.$promise = promise;
  583. value.$resolved = false;
  584. return value;
  585. }
  586. // instance call
  587. return promise;
  588. };
  589. Resource.prototype['$' + name] = function(params, success, error) {
  590. if (isFunction(params)) {
  591. error = success; success = params; params = {};
  592. }
  593. var result = Resource[name].call(this, params, this, success, error);
  594. return result.$promise || result;
  595. };
  596. });
  597. Resource.bind = function(additionalParamDefaults) {
  598. return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
  599. };
  600. return Resource;
  601. }
  602. return resourceFactory;
  603. }];
  604. });
  605. })(window, window.angular);