angular-resource.js 23 KB

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