angular-gem 1.2.2 → 1.2.3

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