2 * @license AngularJS v1.4.8
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 any of the 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|Promise}` – timeout in milliseconds, or {@link ng.$q promise} that
159 * should abort the request when resolved.
160 * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
162 * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)
163 * for more information.
164 * - **`responseType`** - `{string}` - see
165 * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
166 * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
167 * `response` and `responseError`. Both `response` and `responseError` interceptors get called
168 * with `http response` object. See {@link ng.$http $http interceptors}.
170 * @param {Object} options Hash with custom settings that should extend the
171 * default `$resourceProvider` behavior. The only supported option is
175 * - **`stripTrailingSlashes`** – {boolean} – If true then the trailing
176 * slashes from any calculated URL will be stripped. (Defaults to true.)
178 * @returns {Object} A resource "class" object with methods for the default set of resource actions
179 * optionally extended with custom `actions`. The default set contains these actions:
181 * { 'get': {method:'GET'},
182 * 'save': {method:'POST'},
183 * 'query': {method:'GET', isArray:true},
184 * 'remove': {method:'DELETE'},
185 * 'delete': {method:'DELETE'} };
188 * Calling these methods invoke an {@link ng.$http} with the specified http method,
189 * destination and parameters. When the data is returned from the server then the object is an
190 * instance of the resource class. The actions `save`, `remove` and `delete` are available on it
191 * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
192 * read, update, delete) on server-side data like this:
194 * var User = $resource('/user/:userId', {userId:'@id'});
195 * var user = User.get({userId:123}, function() {
201 * It is important to realize that invoking a $resource object method immediately returns an
202 * empty reference (object or array depending on `isArray`). Once the data is returned from the
203 * server the existing reference is populated with the actual data. This is a useful trick since
204 * usually the resource is assigned to a model which is then rendered by the view. Having an empty
205 * object results in no rendering, once the data arrives from the server then the object is
206 * populated with the data and the view automatically re-renders itself showing the new data. This
207 * means that in most cases one never has to write a callback function for the action methods.
209 * The action methods on the class object or instance object can be invoked with the following
212 * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
213 * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
214 * - non-GET instance actions: `instance.$action([parameters], [success], [error])`
217 * Success callback is called with (value, responseHeaders) arguments, where the value is
218 * the populated resource instance or collection object. The error callback is called
219 * with (httpResponse) argument.
221 * Class actions return empty instance (with additional properties below).
222 * Instance actions return promise of the action.
224 * The Resource instances and collection have these additional properties:
226 * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
227 * instance or collection.
229 * On success, the promise is resolved with the same resource instance or collection object,
230 * updated with data from server. This makes it easy to use in
231 * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
232 * rendering until the resource(s) are loaded.
234 * On failure, the promise is resolved with the {@link ng.$http http response} object, without
235 * the `resource` property.
237 * If an interceptor object was provided, the promise will instead be resolved with the value
238 * returned by the interceptor.
240 * - `$resolved`: `true` after first server interaction is completed (either with success or
241 * rejection), `false` before that. Knowing if the Resource has been resolved is useful in
246 * # Credit card resource
249 // Define CreditCard class
250 var CreditCard = $resource('/user/:userId/card/:cardId',
251 {userId:123, cardId:'@id'}, {
252 charge: {method:'POST', params:{charge:true}}
255 // We can retrieve a collection from the server
256 var cards = CreditCard.query(function() {
257 // GET: /user/123/card
258 // server returns: [ {id:456, number:'1234', name:'Smith'} ];
261 // each item is an instance of CreditCard
262 expect(card instanceof CreditCard).toEqual(true);
263 card.name = "J. Smith";
264 // non GET methods are mapped onto the instances
266 // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
267 // server returns: {id:456, number:'1234', name: 'J. Smith'};
269 // our custom method is mapped as well.
270 card.$charge({amount:9.99});
271 // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
274 // we can create an instance as well
275 var newCard = new CreditCard({number:'0123'});
276 newCard.name = "Mike Smith";
278 // POST: /user/123/card {number:'0123', name:'Mike Smith'}
279 // server returns: {id:789, number:'0123', name: 'Mike Smith'};
280 expect(newCard.id).toEqual(789);
283 * The object returned from this function execution is a resource "class" which has "static" method
284 * for each action in the definition.
286 * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
288 * When the data is returned from the server then the object is an instance of the resource type and
289 * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
290 * operations (create, read, update, delete) on server-side data.
293 var User = $resource('/user/:userId', {userId:'@id'});
294 User.get({userId:123}, function(user) {
300 * It's worth noting that the success callback for `get`, `query` and other methods gets passed
301 * in the response that came from the server as well as $http header getter function, so one
302 * could rewrite the above example and get access to http headers as:
305 var User = $resource('/user/:userId', {userId:'@id'});
306 User.get({userId:123}, function(u, getResponseHeaders){
308 u.$save(function(u, putResponseHeaders) {
309 //u => saved user object
310 //putResponseHeaders => $http header getter
315 * You can also access the raw `$http` promise via the `$promise` property on the object returned
318 var User = $resource('/user/:userId', {userId:'@id'});
319 User.get({userId:123})
320 .$promise.then(function(user) {
325 * # Creating a custom 'PUT' request
326 * In this example we create a custom method on our resource to make a PUT request
328 * var app = angular.module('app', ['ngResource', 'ngRoute']);
330 * // Some APIs expect a PUT request in the format URL/object/ID
331 * // Here we are creating an 'update' method
332 * app.factory('Notes', ['$resource', function($resource) {
333 * return $resource('/notes/:id', null,
335 * 'update': { method:'PUT' }
339 * // In our controller we get the ID from the URL using ngRoute and $routeParams
340 * // We pass in $routeParams and our Notes factory along with $scope
341 * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
342 function($scope, $routeParams, Notes) {
343 * // First get a note object from the factory
344 * var note = Notes.get({ id:$routeParams.id });
347 * // Now call update passing in the ID first then the object you are updating
348 * Notes.update({ id:$id }, note);
350 * // This will PUT /notes/ID with the note object in the request payload
354 angular.module('ngResource', ['ng']).
355 provider('$resource', function() {
356 var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^\/]*/;
360 // Strip slashes by default
361 stripTrailingSlashes: true,
363 // Default actions configuration
365 'get': {method: 'GET'},
366 'save': {method: 'POST'},
367 'query': {method: 'GET', isArray: true},
368 'remove': {method: 'DELETE'},
369 'delete': {method: 'DELETE'}
373 this.$get = ['$http', '$q', function($http, $q) {
375 var noop = angular.noop,
376 forEach = angular.forEach,
377 extend = angular.extend,
379 isFunction = angular.isFunction;
382 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
383 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set
384 * (pchar) allowed in path segments:
386 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
387 * pct-encoded = "%" HEXDIG HEXDIG
388 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
389 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
390 * / "*" / "+" / "," / ";" / "="
392 function encodeUriSegment(val) {
393 return encodeUriQuery(val, true).
394 replace(/%26/gi, '&').
395 replace(/%3D/gi, '=').
396 replace(/%2B/gi, '+');
401 * This method is intended for encoding *key* or *value* parts of query component. We need a
402 * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't
403 * have to be encoded per http://tools.ietf.org/html/rfc3986:
404 * query = *( pchar / "/" / "?" )
405 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
406 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
407 * pct-encoded = "%" HEXDIG HEXDIG
408 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
409 * / "*" / "+" / "," / ";" / "="
411 function encodeUriQuery(val, pctEncodeSpaces) {
412 return encodeURIComponent(val).
413 replace(/%40/gi, '@').
414 replace(/%3A/gi, ':').
415 replace(/%24/g, '$').
416 replace(/%2C/gi, ',').
417 replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
420 function Route(template, defaults) {
421 this.template = template;
422 this.defaults = extend({}, provider.defaults, defaults);
427 setUrlParams: function(config, params, actionUrl) {
429 url = actionUrl || self.template,
432 protocolAndDomain = '';
434 var urlParams = self.urlParams = {};
435 forEach(url.split(/\W/), function(param) {
436 if (param === 'hasOwnProperty') {
437 throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name.");
439 if (!(new RegExp("^\\d+$").test(param)) && param &&
440 (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) {
441 urlParams[param] = true;
444 url = url.replace(/\\:/g, ':');
445 url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) {
446 protocolAndDomain = match;
450 params = params || {};
451 forEach(self.urlParams, function(_, urlParam) {
452 val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
453 if (angular.isDefined(val) && val !== null) {
454 encodedVal = encodeUriSegment(val);
455 url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) {
456 return encodedVal + p1;
459 url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match,
460 leadingSlashes, tail) {
461 if (tail.charAt(0) == '/') {
464 return leadingSlashes + tail;
470 // strip trailing slashes and set the url (unless this behavior is specifically disabled)
471 if (self.defaults.stripTrailingSlashes) {
472 url = url.replace(/\/+$/, '') || '/';
475 // then replace collapse `/.` if found in the last URL path segment before the query
476 // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
477 url = url.replace(/\/\.(?=\w+($|\?))/, '.');
478 // replace escaped `/\.` with `/.`
479 config.url = protocolAndDomain + url.replace(/\/\\\./, '/.');
482 // set params - delegate param encoding to $http
483 forEach(params, function(value, key) {
484 if (!self.urlParams[key]) {
485 config.params = config.params || {};
486 config.params[key] = value;
493 function resourceFactory(url, paramDefaults, actions, options) {
494 var route = new Route(url, options);
496 actions = extend({}, provider.defaults.actions, actions);
498 function extractParams(data, actionParams) {
500 actionParams = extend({}, paramDefaults, actionParams);
501 forEach(actionParams, function(value, key) {
502 if (isFunction(value)) { value = value(); }
503 ids[key] = value && value.charAt && value.charAt(0) == '@' ?
504 lookupDottedPath(data, value.substr(1)) : value;
509 function defaultResponseInterceptor(response) {
510 return response.resource;
513 function Resource(value) {
514 shallowClearAndCopy(value || {}, this);
517 Resource.prototype.toJSON = function() {
518 var data = extend({}, this);
519 delete data.$promise;
520 delete data.$resolved;
524 forEach(actions, function(action, name) {
525 var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);
527 Resource[name] = function(a1, a2, a3, a4) {
528 var params = {}, data, success, error;
530 /* jshint -W086 */ /* (purposefully fall through case statements) */
531 switch (arguments.length) {
538 if (isFunction(a2)) {
539 if (isFunction(a1)) {
555 if (isFunction(a1)) success = a1;
556 else if (hasBody) data = a1;
561 throw $resourceMinErr('badargs',
562 "Expected up to 4 arguments [params, data, success, error], got {0} arguments",
565 /* jshint +W086 */ /* (purposefully fall through case statements) */
567 var isInstanceCall = this instanceof Resource;
568 var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
570 var responseInterceptor = action.interceptor && action.interceptor.response ||
571 defaultResponseInterceptor;
572 var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
575 forEach(action, function(value, key) {
578 httpConfig[key] = copy(value);
585 httpConfig[key] = value;
590 if (hasBody) httpConfig.data = data;
591 route.setUrlParams(httpConfig,
592 extend({}, extractParams(data, action.params || {}), params),
595 var promise = $http(httpConfig).then(function(response) {
596 var data = response.data,
597 promise = value.$promise;
600 // Need to convert action.isArray to boolean in case it is undefined
602 if (angular.isArray(data) !== (!!action.isArray)) {
603 throw $resourceMinErr('badcfg',
604 'Error in resource configuration for action `{0}`. Expected response to ' +
605 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',
606 angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);
609 if (action.isArray) {
611 forEach(data, function(item) {
612 if (typeof item === "object") {
613 value.push(new Resource(item));
615 // Valid JSON values may be string literals, and these should not be converted
616 // into objects. These items will not have access to the Resource prototype
617 // methods, but unfortunately there
622 shallowClearAndCopy(data, value);
623 value.$promise = promise;
627 value.$resolved = true;
629 response.resource = value;
632 }, function(response) {
633 value.$resolved = true;
635 (error || noop)(response);
637 return $q.reject(response);
640 promise = promise.then(
642 var value = responseInterceptor(response);
643 (success || noop)(value, response.headers);
646 responseErrorInterceptor);
648 if (!isInstanceCall) {
649 // we are creating instance / collection
650 // - set the initial promise
651 // - return the instance / collection
652 value.$promise = promise;
653 value.$resolved = false;
663 Resource.prototype['$' + name] = function(params, success, error) {
664 if (isFunction(params)) {
665 error = success; success = params; params = {};
667 var result = Resource[name].call(this, params, this, success, error);
668 return result.$promise || result;
672 Resource.bind = function(additionalParamDefaults) {
673 return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
679 return resourceFactory;
684 })(window, window.angular);