forked from mgonto/restangular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrestangular.js
More file actions
1654 lines (1422 loc) · 59.5 KB
/
Copy pathrestangular.js
File metadata and controls
1654 lines (1422 loc) · 59.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(root, factory) {
/* global define, require */
// https://github.com/umdjs/umd/blob/master/templates/returnExports.js
if (typeof define === 'function' && define.amd) {
define(['lodash', 'angular'], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory(require('lodash'), require('angular'));
} else {
// No global export, Restangular will register itself as Angular.js module
factory(root._, root.angular);
}
}(this, function(_, angular) {
var restangularModule = angular.module('restangular', []);
restangularModule.provider('Restangular', function RestangularProvider() {
this.$get = ['$q', 'Configurer', 'Path', function($q, Configurer, Path) {
// augment `this` provider object with properties
// and a configuration object using the Configurer
Configurer.init(this, {});
return createServiceForConfiguration(this.configuration);
function createServiceForConfiguration(config) {
var service = {};
// Basically new Path(config);
var urlHandler = new config.urlCreatorFactory[config.urlCreator](config);
function restangularizeBase(parent, elem, route, reqParams, fromServer) {
elem[config.restangularFields.route] = route;
elem[config.restangularFields.getRestangularUrl] = _.bind(urlHandler.fetchUrl, urlHandler, elem);
elem[config.restangularFields.getRequestedUrl] = _.bind(urlHandler.fetchRequestedUrl, urlHandler, elem);
elem[config.restangularFields.addRestangularMethod] = _.bind(addRestangularMethodFunction, elem);
elem[config.restangularFields.clone] = _.bind(copyRestangularizedElement, elem, elem);
elem[config.restangularFields.reqParams] = _.isEmpty(reqParams) ? null : reqParams;
elem[config.restangularFields.withHttpConfig] = _.bind(withHttpConfig, elem);
elem[config.restangularFields.plain] = _.bind(stripRestangular, elem, elem);
// Tag element as restangularized
elem[config.restangularFields.restangularized] = true;
// RequestLess connection
elem[config.restangularFields.one] = _.bind(one, elem, elem);
elem[config.restangularFields.all] = _.bind(all, elem, elem);
elem[config.restangularFields.several] = _.bind(several, elem, elem);
elem[config.restangularFields.oneUrl] = _.bind(oneUrl, elem, elem);
elem[config.restangularFields.allUrl] = _.bind(allUrl, elem, elem);
elem[config.restangularFields.fromServer] = !!fromServer;
if (parent && config.shouldSaveParent(route)) {
var parentId = config.getIdFromElem(parent);
var parentUrl = config.getUrlFromElem(parent);
var restangularFieldsForParent = _.union(
_.values(_.pick(config.restangularFields, ['route', 'singleOne', 'parentResource'])),
config.extraFields
);
var parentResource = _.pick(parent, restangularFieldsForParent);
if (config.isValidId(parentId)) {
config.setIdToElem(parentResource, parentId, route);
}
if (config.isValidId(parentUrl)) {
config.setUrlToElem(parentResource, parentUrl, route);
}
elem[config.restangularFields.parentResource] = parentResource;
} else {
elem[config.restangularFields.parentResource] = null;
}
return elem;
}
function one(parent, route, id, singleOne) {
var error;
if (_.isNumber(route) || _.isNumber(parent)) {
error = 'You\'re creating a Restangular entity with the number ';
error += 'instead of the route or the parent. For example, you can\'t call .one(12).';
throw new Error(error);
}
if (_.isUndefined(route)) {
error = 'You\'re creating a Restangular entity either without the path. ';
error += 'For example you can\'t call .one(). Please check if your arguments are valid.';
throw new Error(error);
}
var elem = {};
config.setIdToElem(elem, id, route);
config.setFieldToElem(config.restangularFields.singleOne, elem, singleOne);
return restangularizeElem(parent, elem, route, false);
}
function all(parent, route) {
return restangularizeCollection(parent, [], route, false);
}
function several(parent, route /*, ids */ ) {
var collection = [];
collection[config.restangularFields.ids] = Array.prototype.splice.call(arguments, 2);
return restangularizeCollection(parent, collection, route, false);
}
function oneurl(parent, route, url) {
if (!route) {
throw new Error('Route is mandatory when creating new Restangular objects.');
}
var elem = {};
config.setUrlToElem(elem, url, route);
return restangularizeElem(parent, elem, route, false);
}
function allurl(parent, route, url) {
if (!route) {
throw new Error('Route is mandatory when creating new Restangular objects.');
}
var elem = {};
config.setUrlToElem(elem, url, route);
return restangularizeCollection(parent, elem, route, false);
}
// Promises
function restangularizePromise(promise, isCollection, valueToFill) {
promise.call = _.bind(promiseCall, promise);
promise.get = _.bind(promiseGet, promise);
promise[config.restangularFields.restangularCollection] = isCollection;
if (isCollection) {
promise.push = _.bind(promiseCall, promise, 'push');
}
promise.$object = valueToFill;
if (config.restangularizePromiseInterceptor) {
config.restangularizePromiseInterceptor(promise);
}
return promise;
}
function promiseCall(method) {
var deferred = $q.defer();
var callArgs = arguments;
var filledValue = {};
this.then(function(val) {
var params = Array.prototype.slice.call(callArgs, 1);
var func = val[method];
func.apply(val, params);
filledValue = val;
deferred.resolve(val);
});
return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue);
}
function promiseGet(what) {
var deferred = $q.defer();
var filledValue = {};
this.then(function(val) {
filledValue = val[what];
deferred.resolve(filledValue);
});
return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue);
}
function resolvePromise(deferred, response, data, filledValue) {
_.extend(filledValue, data);
// Trigger the full response interceptor.
if (config.fullResponse) {
return deferred.resolve(_.extend(response, {
data: data
}));
} else {
deferred.resolve(data);
}
}
/**
* Removes all restangular properties from the element, returning
* the original element as before it was restangularized. Note that
* if some property names in the original element has clashed with
* Restangular's property names, the original properties may have
* been overwritten and will be removed by this method. To prevent
* name clashes, use `setRestangularFields`.
*
* @param {Object} elem The restangularized element
* @return {Object} The element without any of the
* properties added by Restangular
*/
function stripRestangular(elem) {
// if the element is a collection, then create a new one
// and add each original element, stripped, to it.
if (_.isArray(elem)) {
var array = [];
_.each(elem, function(value) {
array.push(config.isRestangularized(value) ? stripRestangular(value) : value);
});
return array;
} else {
// if the element is a single object, then just
// remove all Restangular properties (except id)
return _.omit(elem, _.values(_.omit(config.restangularFields, 'id')));
}
}
function addCustomOperation(elem) {
elem[config.restangularFields.customOperation] = _.bind(customFunction, elem);
var requestMethods = {
get: customFunction,
delete: customFunction
};
_.each(['put', 'patch', 'post'], function(name) {
requestMethods[name] = function(operation, elem, path, params, headers) {
return _.bind(customFunction, this)(operation, path, params, headers, elem);
};
});
_.each(requestMethods, function(requestFunc, name) {
var callOperation = name === 'delete' ? 'remove' : name;
_.each(['do', 'custom'], function(alias) {
elem[config.restangularFields[alias + name.toUpperCase()]] = _.bind(requestFunc, elem, callOperation);
});
});
elem[config.restangularFields.customGETLIST] = _.bind(getListFunction, elem);
elem[config.restangularFields.doGETLIST] = elem[config.restangularFields.customGETLIST];
}
/**
* Clones the given element by using `angular.copy` and then
* re-restangularizing the new element.
*
* @param {Object} element The element to clone
* @return {Object} The new cloned element
*/
function copyRestangularizedElement(element) {
var copiedElement = angular.copy(element);
// check if we're dealing with a collection (i.e. an array)
// and restangularize the element using the proper restangularizer,
// element / collection
if (_.isArray(element)) {
return restangularizeCollection(
element[config.restangularFields.parentResource],
copiedElement,
element[config.restangularFields.route],
element[config.restangularFields.fromServer],
element[config.restangularFields.reqParams]
);
}
// not a collection, restangularize it as an element
return restangularizeElem(
element[config.restangularFields.parentResource],
copiedElement,
element[config.restangularFields.route],
element[config.restangularFields.fromServer],
element[config.restangularFields.restangularCollection],
element[config.restangularFields.reqParams]
);
}
function restangularizeElem(parent, element, route, fromServer, collection, reqParams) {
var elem = config.onBeforeElemRestangularized(element, false, route);
var localElem = restangularizeBase(parent, elem, route, reqParams, fromServer);
if (config.useCannonicalId) {
localElem[config.restangularFields.cannonicalId] = config.getIdFromElem(localElem);
}
if (collection) {
localElem[config.restangularFields.getParentList] = function() {
return collection;
};
}
localElem[config.restangularFields.restangularCollection] = false;
localElem[config.restangularFields.get] = _.bind(getFunction, localElem);
localElem[config.restangularFields.getList] = _.bind(getListFunction, localElem);
localElem[config.restangularFields.put] = _.bind(putFunction, localElem);
localElem[config.restangularFields.post] = _.bind(postFunction, localElem);
localElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem);
localElem[config.restangularFields.head] = _.bind(headFunction, localElem);
localElem[config.restangularFields.trace] = _.bind(traceFunction, localElem);
localElem[config.restangularFields.options] = _.bind(optionsFunction, localElem);
localElem[config.restangularFields.patch] = _.bind(patchFunction, localElem);
localElem[config.restangularFields.save] = _.bind(save, localElem);
addCustomOperation(localElem);
return config.transformElem(localElem, false, route, service, true);
}
function restangularizeCollection(parent, element, route, fromServer, reqParams) {
var elem = config.onBeforeElemRestangularized(element, true, route);
var localElem = restangularizeBase(parent, elem, route, reqParams, fromServer);
localElem[config.restangularFields.restangularCollection] = true;
localElem[config.restangularFields.post] = _.bind(postFunction, localElem, null);
localElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem);
localElem[config.restangularFields.head] = _.bind(headFunction, localElem);
localElem[config.restangularFields.trace] = _.bind(traceFunction, localElem);
localElem[config.restangularFields.putElement] = _.bind(putElementFunction, localElem);
localElem[config.restangularFields.options] = _.bind(optionsFunction, localElem);
localElem[config.restangularFields.patch] = _.bind(patchFunction, localElem);
localElem[config.restangularFields.get] = _.bind(getById, localElem);
localElem[config.restangularFields.getList] = _.bind(getListFunction, localElem, null);
addCustomOperation(localElem);
return config.transformElem(localElem, true, route, service, true);
}
function restangularizeCollectionAndElements(parent, element, route, fromServer) {
var collection = restangularizeCollection(parent, element, route, fromServer);
_.each(collection, function(elem) {
if (elem) {
restangularizeElem(parent, elem, route, fromServer);
}
});
return collection;
}
function getById(id, reqParams, headers) {
return this.customGET(id.toString(), reqParams, headers);
}
function putElementFunction(idx, params, headers) {
var __this = this;
var elemToPut = this[idx];
var deferred = $q.defer();
var filledArray = [];
filledArray = config.transformElem(filledArray, true, elemToPut[config.restangularFields.route], service);
elemToPut.put(params, headers).then(function(serverElem) {
var newArray = copyRestangularizedElement(__this);
newArray[idx] = serverElem;
filledArray = newArray;
deferred.resolve(newArray);
}, function(response) {
deferred.reject(response);
});
return restangularizePromise(deferred.promise, true, filledArray);
}
function parseResponse(resData, operation, route, fetchUrl, response, deferred) {
var data = config.responseExtractor(resData, operation, route, fetchUrl, response, deferred);
var etag = response.headers('ETag');
if (data && etag) {
data[config.restangularFields.etag] = etag;
}
return data;
}
/**
* Gets a collection from the remote API. Bound to both Restangularized
* elements (getList) and collections (getList) (see examples).
*
* @param {String} what The collection name to fetch when used on elements,
* null when bound to collection.
* @param {Object} reqParams Query parameters for the request
* @param {Object} headers Headers for the request
* @return {Promise<Array>} Promise, resolves to the collection array
*
* @example
* // As used on collection
* Restangular.all('accounts').getList();
*
* // As used on element
* Restangular.one('account', 1).getList('users');
*/
function getListFunction(what, reqParams, headers) {
var __this = this;
var deferred = $q.defer();
var operation = 'getList';
var url = urlHandler.fetchurl(this, what);
var whatFetched = what || __this[config.restangularFields.route];
var request = config.fullRequestInterceptor(null, operation,
whatFetched, url, headers || {}, reqParams || {}, this[config.restangularFields.httpConfig] || {});
var filledArray = [];
filledArray = config.transformElem(filledArray, true, whatFetched, service);
var method = 'getList';
if (config.jsonp) {
method = 'jsonp';
}
var okCallback = function(response) {
var resData = response.data;
var fullParams = response.config.params;
var data = parseResponse(resData, operation, whatFetched, url, response, deferred);
// support empty response for getList() calls (some APIs respond with 204 and empty body)
if (_.isUndefined(data) || '' === data) {
data = [];
}
if (!_.isArray(data)) {
throw new Error('Response for getList SHOULD be an array and not an object or something else');
}
if (true === config.plainByDefault) {
return resolvePromise(deferred, response, data, filledArray);
}
var processedData = _.map(data, function(elem) {
if (!__this[config.restangularFields.restangularCollection]) {
return restangularizeElem(__this, elem, what, true, data);
} else {
return restangularizeElem(__this[config.restangularFields.parentResource],
elem, __this[config.restangularFields.route], true, data);
}
});
processedData = _.extend(data, processedData);
if (!__this[config.restangularFields.restangularCollection]) {
resolvePromise(
deferred,
response,
restangularizeCollection(
__this,
processedData,
what,
true,
fullParams
),
filledArray
);
} else {
resolvePromise(
deferred,
response,
restangularizeCollection(
__this[config.restangularFields.parentResource],
processedData,
__this[config.restangularFields.route],
true,
fullParams
),
filledArray
);
}
};
var errorCallback = function error(response) {
if (response.status === 304 && __this[config.restangularFields.restangularCollection]) {
resolvePromise(deferred, response, __this, filledArray);
} else if (_.every(config.errorInterceptors, function(cb) {
return cb(response, deferred, okCallback) !== false;
})) {
// triggered if no callback returns false
deferred.reject(response);
}
};
// create a resource
var resource = urlHandler.resource(
this,
request.httpConfig,
request.headers,
request.params,
what,
this[config.restangularFields.etag],
operation
);
resource[method]().then(okCallback, errorCallback);
// return
return restangularizePromise(deferred.promise, true, filledArray);
}
function withHttpConfig(httpConfig) {
this[config.restangularFields.httpConfig] = httpConfig;
return this;
}
function save(params, headers) {
if (this[config.restangularFields.fromServer]) {
return this[config.restangularFields.put](params, headers);
} else {
return _.bind(elemFunction, this)('post', undefined, params, undefined, headers);
}
}
function elemFunction(operation, what, params, obj, headers) {
var __this = this;
var deferred = $q.defer();
var resParams = params || {};
var route = what || this[config.restangularFields.route];
var fetchUrl = urlHandler.fetchurl(this, what);
var callObj = obj || this;
// fallback to etag on restangular object (since for custom methods we probably don't explicitly specify the etag field)
var etag = callObj[config.restangularFields.etag] || (operation !== 'post' ? this[config.restangularFields.etag] : null);
if (_.isObject(callObj) && config.isRestangularized(callObj)) {
callObj = stripRestangular(callObj);
}
var request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl,
headers || {}, resParams || {}, this[config.restangularFields.httpConfig] || {});
var filledObject = {};
filledObject = config.transformElem(filledObject, false, route, service);
// Overriding HTTP Method
var method = operation;
var callHeaders = _.extend({}, request.headers);
var isOverrideOperation = config.isOverridenMethod(operation);
if (isOverrideOperation) {
method = 'post';
callHeaders = _.extend(callHeaders, {
'X-HTTP-Method-Override': operation === 'remove' ? 'DELETE' : operation.toUpperCase()
});
} else if (config.jsonp && method === 'get') {
method = 'jsonp';
}
var okCallback = function(response) {
var resData = response.data;
var fullParams = response.config.params;
var elem = parseResponse(resData, operation, route, fetchUrl, response, deferred);
// accept 0 as response
if (elem !== null && elem !== undefined && elem !== '') {
var data;
if (true === config.plainByDefault) {
return resolvePromise(deferred, response, elem, filledObject);
}
if (operation === 'post' && !__this[config.restangularFields.restangularCollection]) {
data = restangularizeElem(
__this[config.restangularFields.parentResource],
elem,
route,
true,
null,
fullParams
);
resolvePromise(deferred, response, data, filledObject);
} else {
data = restangularizeElem(
__this[config.restangularFields.parentResource],
elem,
__this[config.restangularFields.route],
true,
null,
fullParams
);
data[config.restangularFields.singleOne] = __this[config.restangularFields.singleOne];
resolvePromise(deferred, response, data, filledObject);
}
} else {
resolvePromise(deferred, response, undefined, filledObject);
}
};
var errorCallback = function(response) {
if (response.status === 304 && config.isSafe(operation)) {
resolvePromise(deferred, response, __this, filledObject);
} else if (_.every(config.errorInterceptors, function(cb) {
return cb(response, deferred, okCallback) !== false;
})) {
// triggered if no callback returns false
deferred.reject(response);
}
};
var resource = urlHandler.resource(
this,
request.httpConfig,
callHeaders,
request.params,
what,
etag,
method
);
var requestObject;
if (!config.isSafe(operation)) {
requestObject = request.element;
} else if (isOverrideOperation) {
requestObject = {};
}
resource[method](requestObject).then(okCallback, errorCallback);
return restangularizePromise(deferred.promise, false, filledObject);
}
function getFunction(params, headers) {
return _.bind(elemFunction, this)('get', undefined, params, undefined, headers);
}
function deleteFunction(params, headers) {
return _.bind(elemFunction, this)('remove', undefined, params, undefined, headers);
}
function putFunction(params, headers) {
return _.bind(elemFunction, this)('put', undefined, params, undefined, headers);
}
function postFunction(what, elem, params, headers) {
return _.bind(elemFunction, this)('post', what, params, elem, headers);
}
function headFunction(params, headers) {
return _.bind(elemFunction, this)('head', undefined, params, undefined, headers);
}
function traceFunction(params, headers) {
return _.bind(elemFunction, this)('trace', undefined, params, undefined, headers);
}
function optionsFunction(params, headers) {
return _.bind(elemFunction, this)('options', undefined, params, undefined, headers);
}
function patchFunction(elem, params, headers) {
return _.bind(elemFunction, this)('patch', undefined, params, elem, headers);
}
function customFunction(operation, path, params, headers, elem) {
return _.bind(elemFunction, this)(operation, path, params, elem, headers);
}
function addRestangularMethodFunction(name, operation, path, defaultParams, defaultHeaders, defaultElem) {
var bindedFunction;
if (operation === 'getList') {
bindedFunction = _.bind(getListFunction, this, path);
} else {
bindedFunction = _.bind(customFunction, this, operation, path);
}
var createdFunction = function(params, headers, elem) {
var callParams = _.defaults({
params: params,
headers: headers,
elem: elem
}, {
params: defaultParams,
headers: defaultHeaders,
elem: defaultElem
});
return bindedFunction(callParams.params, callParams.headers, callParams.elem);
};
if (config.isSafe(operation)) {
this[name] = createdFunction;
} else {
this[name] = function(elem, params, headers) {
return createdFunction(params, headers, elem);
};
}
}
function withConfigurationFunction(configurer) {
var newConfig = angular.copy(_.omit(config, 'configuration'));
Configurer.init(newConfig, newConfig);
configurer(newConfig);
return createServiceForConfiguration(newConfig);
}
function toService(route, parent) {
var knownCollectionMethods = _.values(config.restangularFields);
var serv = {};
var collection = (parent || service).all(route);
serv.one = _.bind(one, (parent || service), parent, route);
serv.post = _.bind(collection.post, collection);
serv.getList = _.bind(collection.getList, collection);
serv.withHttpConfig = _.bind(collection.withHttpConfig, collection);
serv.get = _.bind(collection.get, collection);
for (var prop in collection) {
if (collection.hasOwnProperty(prop) && _.isFunction(collection[prop]) && !_.includes(knownCollectionMethods, prop)) {
serv[prop] = _.bind(collection[prop], collection);
}
}
return serv;
}
Configurer.init(service, config);
service.copy = _.bind(copyRestangularizedElement, service);
service.service = _.bind(toService, service);
service.withConfig = _.bind(withConfigurationFunction, service);
service.one = _.bind(one, service, null);
service.all = _.bind(all, service, null);
service.several = _.bind(several, service, null);
service.oneUrl = _.bind(oneUrl, service, null);
service.allUrl = _.bind(allUrl, service, null);
service.stripRestangular = _.bind(stripRestangular, service);
service.restangularizeElement = _.bind(restangularizeElem, service);
service.restangularizeCollection = _.bind(restangularizeCollectionAndElements, service);
return service;
}
}];
});
restangularModule.factory('BaseCreator', ['$http', function BaseCreatorFactory($http) {
/**
* Base URL Creator. Base prototype for everything related to it
**/
function BaseCreator(config) {
this.config = config;
}
BaseCreator.prototype.setConfig = function(config) {
this.config = config;
return this;
};
BaseCreator.prototype.parentsArray = function(current) {
var parents = [];
while (current) {
parents.push(current);
current = current[this.config.restangularFields.parentResource];
}
return parents.reverse();
};
/**
* Creates an object "resource" with one method for each key
* in the given methodConfigurations. The method will make an $http
* request to the given URL using the HTTP verb, query parameters and
* headers given in the methodConfiguration. Query parameters will be
* extended (and possibly overwritten) with the default query parameters
* defined in the current configuration.
*
* If the HTTP verb given in the configuration is unsafe (sends data),
* the corresponding produced method will take one argument, which is
* the data to be sent in the request.
*
* @param {String} url The URL for the resource
* @param {Object} methodConfigurations Configuration options for resource methods
*
* @example
* var methodConfigs = {
* getList: {
* method: "GET",
* params: {},
* headers: {}
* },
* get: {
* method: "GET",
* params: {
* q: "abc"
* },
* headers: {
* "X-FooBar: "Yes"
* }
* },
* post: {
* method: "POST",
* params: {},
* headers: {}
* },
* fooCustom: {
* method: "POST",
* params: {one: 'value'},
* headers: {'X-Some-Thing': 123}
* }
* };
* var resource = baseCreator.createRestangularResource('http://server.com', methodConfigs);
* resource.fooCustom({some: 'data'});
* // -> POST http://server.com?one=value
* // with data {some: 'data'}
* // with headers {'X-Some-Thing': 123}
*/
BaseCreator.prototype.createRestangularResource = function(url, methodConfigurations) {
var _this = this;
var resource = {};
_.each(methodConfigurations, function(methodConf, methodName) {
// Add default parameters
methodConf.params = _.extend(methodConf.params, _this.config.defaultRequestParams[methodConf.method.toLowerCase()]);
if (_this.config.isSafe(methodConf.method)) {
resource[methodName] = function() {
return $http(_.extend(methodConf, {
url: url
}));
};
} else {
resource[methodName] = function(data) {
return $http(_.extend(methodConf, {
url: url,
data: data
}));
};
}
});
return resource;
};
/**
* Creates a resource
* @param {object} current The current element
* @param {Object} localHttpConfig HTTP configuration options
* @param {Object} callHeaders Common headers for all requests
* @param {Object} callParams Common query params for all requests
* @param {String} what Path of the resource
* @param {String} etag ETag to use in the request
* @param {String} operation HTTP verb (or getList)
* @return {Object} An object representing a resource
*/
BaseCreator.prototype.resource = function(current, localHttpConfig, callHeaders, callParams, what, etag, operation) {
// extend the query parameters with default query params from config
var params = _.defaults(callParams || {}, this.config.defaultRequestParams.common);
// extend headers with default headers from config
var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders);
// if we have an ETag, use it in the header
if (etag) {
if (!this.config.isSafe(operation)) {
// Use if-match header for POST, PUT, DELETE etc
// to prevent overwriting with old data
headers['If-Match'] = etag;
} else {
// Use if-none-match on save methods for caching
headers['If-None-Match'] = etag;
}
}
var url = this.base(current);
if (what || what === 0) {
var add = '';
if (!/\/$/.test(url)) {
add += '/';
}
add += what;
url += add;
}
if (this.config.suffix &&
url.indexOf(this.config.suffix, url.length - this.config.suffix.length) === -1 &&
!this.config.getUrlFromElem(current)) {
url += this.config.suffix;
}
current[this.config.restangularFields.httpConfig] = undefined;
return this.createRestangularResource(url, {
getList: this.config.withHttpValues({
method: 'GET',
params: params,
headers: headers
}, localHttpConfig),
get: this.config.withHttpValues({
method: 'GET',
params: params,
headers: headers
}, localHttpConfig),
jsonp: this.config.withHttpValues({
method: 'jsonp',
params: params,
headers: headers
}, localHttpConfig),
put: this.config.withHttpValues({
method: 'PUT',
params: params,
headers: headers
}, localHttpConfig),
post: this.config.withHttpValues({
method: 'POST',
params: params,
headers: headers
}, localHttpConfig),
remove: this.config.withHttpValues({
method: 'DELETE',
params: params,
headers: headers
}, localHttpConfig),
head: this.config.withHttpValues({
method: 'HEAD',
params: params,
headers: headers
}, localHttpConfig),
trace: this.config.withHttpValues({
method: 'TRACE',
params: params,
headers: headers
}, localHttpConfig),
options: this.config.withHttpValues({
method: 'OPTIONS',
params: params,
headers: headers
}, localHttpConfig),
patch: this.config.withHttpValues({
method: 'PATCH',
params: params,
headers: headers
}, localHttpConfig)
});
};
return BaseCreator;
}]);
restangularModule.factory('Path', ['BaseCreator', function PathFactory(BaseCreator) {
/**
* This is the Path URL creator. It uses Path to show Hierarchy in the Rest API.
* This means that if you have an Account that then has a set of Buildings, a URL to a building
* would be /accounts/123/buildings/456
*
* It's a subclass of BaseCreator.
*
* @param {Object} config Configuration object given to the constructor.
**/
function Path(config) {
// call "super" constructor
// Part of subclassing Path from BaseCreator
BaseCreator.call(this, config);
}
// Part of subclassing Path from BaseCreator
Path.prototype = new BaseCreator();
// Part of subclassing Path from BaseCreator
Path.prototype.constructor = BaseCreator;
/**
* Normalizes a URL by replacing multiple consecutive slashes,
* backslashes, or escaped slashes with single slashes. Leaves
* the (optional) protocol part intact.
*
* @param {String} url A URL
* @return {String} A normalized URL
*/
Path.prototype.normalizeUrl = function(url) {
// Regex match the given url and split it into three parts
// 0. (parts[0]): the full match
// 1. (parts[1]): the protocol part
// 2. (parst[2]): the rest
var parts = /((?:http[s]?:)?\/\/)?(.*)?/.exec(url);
// replace any duplicate backslashes or slashes or combination
// with a single slash in the path part
parts[2] = parts[2].replace(/[\\\/]+/g, '/');
return (typeof parts[1] !== 'undefined') ? parts[1] + parts[2] : parts[2];
};
Path.prototype.base = function(current) {
var __this = this;
return _.reduce(this.parentsArray(current), function(acum, elem) {
var elemUrl;
var elemSelfLink = __this.config.getUrlFromElem(elem);
if (elemSelfLink) {
if (__this.config.isAbsoluteurl(elemSelfLink)) {
return elemSelfLink;
} else {
elemUrl = elemSelfLink;
}
} else {
elemUrl = elem[__this.config.restangularFields.route];
if (elem[__this.config.restangularFields.restangularCollection]) {
var ids = elem[__this.config.restangularFields.ids];
if (ids) {
elemUrl += '/' + ids.join(',');
}
} else {
var elemId;
if (__this.config.useCannonicalId) {