2 * @license AngularJS v1.4.10
3 * (c) 2010-2015 Google, Inc. http://angularjs.org
6 (function(window, angular, undefined) {'use strict';
8 var $resourceMinErr = angular.$$minErr('$resource');
10 // Helper functions and regex to lookup a dotted path on an object
11 // stopping at undefined/null. The path must be composed of ASCII
12 // identifiers (just like $parse)
13 var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;
15 function isValidDottedPath(path) {
16 return (path != null && path !== '' && path !== 'hasOwnProperty' &&
17 MEMBER_NAME_REGEX.test('.' + path));
20 function lookupDottedPath(obj, path) {
21 if (!isValidDottedPath(path)) {
22 throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path);
24 var keys = path.split('.');
25 for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) {
27 obj = (obj !== null) ? obj[key] : undefined;
33 * Create a shallow copy of an object and clear other fields from the destination
35 function shallowClearAndCopy(src, dst) {
38 angular.forEach(dst, function(value, key) {
42 for (var key in src) {
43 if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
58 * The `ngResource` module provides interaction support with RESTful services
59 * via the $resource service.
62 * <div doc-module-components="ngResource"></div>
64 * See {@link ngResource.$resource `$resource`} for usage.
73 * A factory which creates a resource object that lets you interact with
74 * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
76 * The returned resource object has action methods which provide high-level behaviors without
77 * the need to interact with the low level {@link ng.$http $http} service.
79 * Requires the {@link ngResource `ngResource`} module to be installed.
81 * By default, trailing slashes will be stripped from the calculated URLs,
82 * which can pose problems with server backends that do not expect that
83 * behavior. This can be disabled by configuring the `$resourceProvider` like
87 app.config(['$resourceProvider', function($resourceProvider) {
88 // Don't strip trailing slashes from calculated URLs
89 $resourceProvider.defaults.stripTrailingSlashes = false;
93 * @param {string} url A parameterized URL template with parameters prefixed by `:` as in
94 * `/user/:username`. If you are using a URL with a port number (e.g.
95 * `http://example.com:8080/api`), it will be respected.
97 * If you are using a url with a suffix, just add the suffix, like this:
98 * `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`
99 * or even `$resource('http://example.com/resource/:resource_id.:format')`
100 * If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be
101 * collapsed down to a single `.`. If you need this sequence to appear and not collapse then you
102 * can escape it with `/\.`.
104 * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
105 * `actions` methods. If a parameter value is a function, it will be executed every time
106 * when a param value needs to be obtained for a request (unless the param was overridden).
108 * Each key value in the parameter object is first bound to url template if present and then any
109 * excess keys are appended to the url search query after the `?`.
111 * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
112 * URL `/path/greet?salutation=Hello`.
114 * If the parameter value is prefixed with `@` then the value for that parameter will be extracted
115 * from the corresponding property on the `data` object (provided when calling an action method). For
116 * example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam`
117 * will be `data.someProp`.
119 * @param {Object.<Object>=} actions Hash with declaration of custom actions that should extend
120 * the default set of resource actions. The declaration should be created in the format of {@link
121 * ng.$http#usage $http.config}:
123 * {action1: {method:?, params:?, isArray:?, headers:?, ...},
124 * action2: {method:?, params:?, isArray:?, headers:?, ...},
129 * - **`action`** – {string} – The name of action. This name becomes the name of the method on
130 * your resource object.
131 * - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,
132 * `DELETE`, `JSONP`, etc).
133 * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of
134 * the parameter value is a function, it will be executed every time when a param value needs to
135 * be obtained for a request (unless the param was overridden).
136 * - **`url`** – {string} – action specific `url` override. The url templating is supported just
137 * like for the resource-level urls.
138 * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,
139 * see `returns` section.
140 * - **`transformRequest`** –
141 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
142 * transform function or an array of such functions. The transform function takes the http
143 * request body and headers and returns its transformed (typically serialized) version.
144 * By default, transformRequest will contain one function that checks if the request data is
145 * an object and serializes to using `angular.toJson`. To prevent this behavior, set
146 * `transformRequest` to an empty array: `transformRequest: []`
147 * - **`transformResponse`** –
148 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
149 * transform function or an array of such functions. The transform function takes the http
150 * response body and headers and returns its transformed (typically deserialized) version.
151 * By default, transformResponse will contain one function that checks if the response looks like
152 * a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, set
153 * `transformResponse` to an empty array: `transformResponse: []`
154 * - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
155 * GET request, otherwise if a cache instance built with
156 * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
158 * - **`timeout`** – `{number}` – timeout in milliseconds.<br />
159 * **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are
160 * **not** supported in $resource, because the same value would be used for multiple requests.
161 * If you need support for cancellable $resource actions, you should upgrade to version 1.5 or
163 * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
165 * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)
166 * for more information.
167 * - **`responseType`** - `{string}` - see
168 * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
169 * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
170 * `response` and `responseError`. Both `response` and `responseError` interceptors get called
171 * with `http response` object. See {@link ng.$http $http interceptors}.
173 * @param {Object} options Hash with custom settings that should extend the
174 * default `$resourceProvider` behavior. The only supported option is
178 * - **`stripTrailingSlashes`** – {boolean} – If true then the trailing
179 * slashes from any calculated URL will be stripped. (Defaults to true.)
181 * @returns {Object} A resource "class" object with methods for the default set of resource actions
182 * optionally extended with custom `actions`. The default set contains these actions:
184 * { 'get': {method:'GET'},
185 * 'save': {method:'POST'},
186 * 'query': {method:'GET', isArray:true},
187 * 'remove': {method:'DELETE'},
188 * 'delete': {method:'DELETE'} };
191 * Calling these methods invoke an {@link ng.$http} with the specified http method,
192 * destination and parameters. When the data is returned from the server then the object is an
193 * instance of the resource class. The actions `save`, `remove` and `delete` are available on it
194 * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
195 * read, update, delete) on server-side data like this:
197 * var User = $resource('/user/:userId', {userId:'@id'});
198 * var user = User.get({userId:123}, function() {
204 * It is important to realize that invoking a $resource object method immediately returns an
205 * empty reference (object or array depending on `isArray`). Once the data is returned from the
206 * server the existing reference is populated with the actual data. This is a useful trick since
207 * usually the resource is assigned to a model which is then rendered by the view. Having an empty
208 * object results in no rendering, once the data arrives from the server then the object is
209 * populated with the data and the view automatically re-renders itself showing the new data. This
210 * means that in most cases one never has to write a callback function for the action methods.
212 * The action methods on the class object or instance object can be invoked with the following
215 * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
216 * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
217 * - non-GET instance actions: `instance.$action([parameters], [success], [error])`
220 * Success callback is called with (value, responseHeaders) arguments, where the value is
221 * the populated resource instance or collection object. The error callback is called
222 * with (httpResponse) argument.
224 * Class actions return empty instance (with additional properties below).
225 * Instance actions return promise of the action.
227 * The Resource instances and collection have these additional properties:
229 * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
230 * instance or collection.
232 * On success, the promise is resolved with the same resource instance or collection object,
233 * updated with data from server. This makes it easy to use in
234 * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
235 * rendering until the resource(s) are loaded.
237 * On failure, the promise is rejected with the {@link ng.$http http response} object, without
238 * the `resource` property.
240 * If an interceptor object was provided, the promise will instead be resolved with the value
241 * returned by the interceptor.
243 * - `$resolved`: `true` after first server interaction is completed (either with success or
244 * rejection), `false` before that. Knowing if the Resource has been resolved is useful in
249 * # Credit card resource
252 // Define CreditCard class
253 var CreditCard = $resource('/user/:userId/card/:cardId',
254 {userId:123, cardId:'@id'}, {
255 charge: {method:'POST', params:{charge:true}}
258 // We can retrieve a collection from the server
259 var cards = CreditCard.query(function() {
260 // GET: /user/123/card
261 // server returns: [ {id:456, number:'1234', name:'Smith'} ];
264 // each item is an instance of CreditCard
265 expect(card instanceof CreditCard).toEqual(true);
266 card.name = "J. Smith";
267 // non GET methods are mapped onto the instances
269 // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
270 // server returns: {id:456, number:'1234', name: 'J. Smith'};
272 // our custom method is mapped as well.
273 card.$charge({amount:9.99});
274 // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
277 // we can create an instance as well
278 var newCard = new CreditCard({number:'0123'});
279 newCard.name = "Mike Smith";
281 // POST: /user/123/card {number:'0123', name:'Mike Smith'}
282 // server returns: {id:789, number:'0123', name: 'Mike Smith'};
283 expect(newCard.id).toEqual(789);
286 * The object returned from this function execution is a resource "class" which has "static" method
287 * for each action in the definition.
289 * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
291 * When the data is returned from the server then the object is an instance of the resource type and
292 * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
293 * operations (create, read, update, delete) on server-side data.
296 var User = $resource('/user/:userId', {userId:'@id'});
297 User.get({userId:123}, function(user) {
303 * It's worth noting that the success callback for `get`, `query` and other methods gets passed
304 * in the response that came from the server as well as $http header getter function, so one
305 * could rewrite the above example and get access to http headers as:
308 var User = $resource('/user/:userId', {userId:'@id'});
309 User.get({userId:123}, function(u, getResponseHeaders){
311 u.$save(function(u, putResponseHeaders) {
312 //u => saved user object
313 //putResponseHeaders => $http header getter
318 * You can also access the raw `$http` promise via the `$promise` property on the object returned
321 var User = $resource('/user/:userId', {userId:'@id'});
322 User.get({userId:123})
323 .$promise.then(function(user) {
328 * # Creating a custom 'PUT' request
329 * In this example we create a custom method on our resource to make a PUT request
331 * var app = angular.module('app', ['ngResource', 'ngRoute']);
333 * // Some APIs expect a PUT request in the format URL/object/ID
334 * // Here we are creating an 'update' method
335 * app.factory('Notes', ['$resource', function($resource) {
336 * return $resource('/notes/:id', null,
338 * 'update': { method:'PUT' }
342 * // In our controller we get the ID from the URL using ngRoute and $routeParams
343 * // We pass in $routeParams and our Notes factory along with $scope
344 * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
345 function($scope, $routeParams, Notes) {
346 * // First get a note object from the factory
347 * var note = Notes.get({ id:$routeParams.id });
350 * // Now call update passing in the ID first then the object you are updating
351 * Notes.update({ id:$id }, note);
353 * // This will PUT /notes/ID with the note object in the request payload
357 angular.module('ngResource', ['ng']).
358 provider('$resource', function() {
359 var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^\/]*/;
363 // Strip slashes by default
364 stripTrailingSlashes: true,
366 // Default actions configuration
368 'get': {method: 'GET'},
369 'save': {method: 'POST'},
370 'query': {method: 'GET', isArray: true},
371 'remove': {method: 'DELETE'},
372 'delete': {method: 'DELETE'}
376 this.$get = ['$http', '$log', '$q', function($http, $log, $q) {
378 var noop = angular.noop,
379 forEach = angular.forEach,
380 extend = angular.extend,
382 isFunction = angular.isFunction;
385 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
386 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set
387 * (pchar) allowed in path segments:
389 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
390 * pct-encoded = "%" HEXDIG HEXDIG
391 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
392 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
393 * / "*" / "+" / "," / ";" / "="
395 function encodeUriSegment(val) {
396 return encodeUriQuery(val, true).
397 replace(/%26/gi, '&').
398 replace(/%3D/gi, '=').
399 replace(/%2B/gi, '+');
404 * This method is intended for encoding *key* or *value* parts of query component. We need a
405 * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't
406 * have to be encoded per http://tools.ietf.org/html/rfc3986:
407 * query = *( pchar / "/" / "?" )
408 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
409 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
410 * pct-encoded = "%" HEXDIG HEXDIG
411 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
412 * / "*" / "+" / "," / ";" / "="
414 function encodeUriQuery(val, pctEncodeSpaces) {
415 return encodeURIComponent(val).
416 replace(/%40/gi, '@').
417 replace(/%3A/gi, ':').
418 replace(/%24/g, '$').
419 replace(/%2C/gi, ',').
420 replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
423 function Route(template, defaults) {
424 this.template = template;
425 this.defaults = extend({}, provider.defaults, defaults);
430 setUrlParams: function(config, params, actionUrl) {
432 url = actionUrl || self.template,
435 protocolAndDomain = '';
437 var urlParams = self.urlParams = {};
438 forEach(url.split(/\W/), function(param) {
439 if (param === 'hasOwnProperty') {
440 throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name.");
442 if (!(new RegExp("^\\d+$").test(param)) && param &&
443 (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) {
444 urlParams[param] = true;
447 url = url.replace(/\\:/g, ':');
448 url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) {
449 protocolAndDomain = match;
453 params = params || {};
454 forEach(self.urlParams, function(_, urlParam) {
455 val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
456 if (angular.isDefined(val) && val !== null) {
457 encodedVal = encodeUriSegment(val);
458 url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) {
459 return encodedVal + p1;
462 url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match,
463 leadingSlashes, tail) {
464 if (tail.charAt(0) == '/') {
467 return leadingSlashes + tail;
473 // strip trailing slashes and set the url (unless this behavior is specifically disabled)
474 if (self.defaults.stripTrailingSlashes) {
475 url = url.replace(/\/+$/, '') || '/';
478 // then replace collapse `/.` if found in the last URL path segment before the query
479 // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
480 url = url.replace(/\/\.(?=\w+($|\?))/, '.');
481 // replace escaped `/\.` with `/.`
482 config.url = protocolAndDomain + url.replace(/\/\\\./, '/.');
485 // set params - delegate param encoding to $http
486 forEach(params, function(value, key) {
487 if (!self.urlParams[key]) {
488 config.params = config.params || {};
489 config.params[key] = value;
496 function resourceFactory(url, paramDefaults, actions, options) {
497 var route = new Route(url, options);
499 actions = extend({}, provider.defaults.actions, actions);
501 function extractParams(data, actionParams) {
503 actionParams = extend({}, paramDefaults, actionParams);
504 forEach(actionParams, function(value, key) {
505 if (isFunction(value)) { value = value(); }
506 ids[key] = value && value.charAt && value.charAt(0) == '@' ?
507 lookupDottedPath(data, value.substr(1)) : value;
512 function defaultResponseInterceptor(response) {
513 return response.resource;
516 function Resource(value) {
517 shallowClearAndCopy(value || {}, this);
520 Resource.prototype.toJSON = function() {
521 var data = extend({}, this);
522 delete data.$promise;
523 delete data.$resolved;
527 forEach(actions, function(action, name) {
528 var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);
530 Resource[name] = function(a1, a2, a3, a4) {
531 var params = {}, data, success, error;
533 /* jshint -W086 */ /* (purposefully fall through case statements) */
534 switch (arguments.length) {
541 if (isFunction(a2)) {
542 if (isFunction(a1)) {
558 if (isFunction(a1)) success = a1;
559 else if (hasBody) data = a1;
564 throw $resourceMinErr('badargs',
565 "Expected up to 4 arguments [params, data, success, error], got {0} arguments",
568 /* jshint +W086 */ /* (purposefully fall through case statements) */
570 var isInstanceCall = this instanceof Resource;
571 var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
573 var responseInterceptor = action.interceptor && action.interceptor.response ||
574 defaultResponseInterceptor;
575 var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
578 forEach(action, function(value, key) {
581 httpConfig[key] = copy(value);
588 if (value && !angular.isNumber(value)) {
589 $log.debug('ngResource:\n' +
590 ' Only numeric values are allowed as `timeout`.\n' +
591 ' Promises are not supported in $resource, because the same value would ' +
592 'be used for multiple requests.\n' +
593 ' If you need support for cancellable $resource actions, you should ' +
594 'upgrade to version 1.5 or higher.');
600 if (hasBody) httpConfig.data = data;
601 route.setUrlParams(httpConfig,
602 extend({}, extractParams(data, action.params || {}), params),
605 var promise = $http(httpConfig).then(function(response) {
606 var data = response.data,
607 promise = value.$promise;
610 // Need to convert action.isArray to boolean in case it is undefined
612 if (angular.isArray(data) !== (!!action.isArray)) {
613 throw $resourceMinErr('badcfg',
614 'Error in resource configuration for action `{0}`. Expected response to ' +
615 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',
616 angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);
619 if (action.isArray) {
621 forEach(data, function(item) {
622 if (typeof item === "object") {
623 value.push(new Resource(item));
625 // Valid JSON values may be string literals, and these should not be converted
626 // into objects. These items will not have access to the Resource prototype
627 // methods, but unfortunately there
632 shallowClearAndCopy(data, value);
633 value.$promise = promise;
637 value.$resolved = true;
639 response.resource = value;
642 }, function(response) {
643 value.$resolved = true;
645 (error || noop)(response);
647 return $q.reject(response);
650 promise = promise.then(
652 var value = responseInterceptor(response);
653 (success || noop)(value, response.headers);
656 responseErrorInterceptor);
658 if (!isInstanceCall) {
659 // we are creating instance / collection
660 // - set the initial promise
661 // - return the instance / collection
662 value.$promise = promise;
663 value.$resolved = false;
673 Resource.prototype['$' + name] = function(params, success, error) {
674 if (isFunction(params)) {
675 error = success; success = params; params = {};
677 var result = Resource[name].call(this, params, this, success, error);
678 return result.$promise || result;
682 Resource.bind = function(additionalParamDefaults) {
683 return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
689 return resourceFactory;
694 })(window, window.angular);