angular-resource.js 24 KB

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