-
Notifications
You must be signed in to change notification settings - Fork 838
/
restangular.js
1447 lines (1225 loc) · 51.4 KB
/
restangular.js
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 restangular = angular.module('restangular', []);
restangular.provider('Restangular', function() {
// Configuration
var Configurer = {};
Configurer.init = function(object, config) {
object.configuration = config;
/**
* Those are HTTP safe methods for which there is no need to pass any data with the request.
*/
var safeMethods = ['get', 'head', 'options', 'trace', 'getlist'];
config.isSafe = function(operation) {
return _.includes(safeMethods, operation.toLowerCase());
};
var absolutePattern = /^https?:\/\//i;
config.isAbsoluteUrl = function(string) {
return _.isUndefined(config.absoluteUrl) || _.isNull(config.absoluteUrl) ?
string && absolutePattern.test(string) :
config.absoluteUrl;
};
config.absoluteUrl = _.isUndefined(config.absoluteUrl) ? true : config.absoluteUrl;
object.setSelfLinkAbsoluteUrl = function(value) {
config.absoluteUrl = value;
};
/**
* This is the BaseURL to be used with Restangular
*/
config.baseUrl = _.isUndefined(config.baseUrl) ? '' : config.baseUrl;
object.setBaseUrl = function(newBaseUrl) {
config.baseUrl = /\/$/.test(newBaseUrl) ?
newBaseUrl.substring(0, newBaseUrl.length - 1) :
newBaseUrl;
return this;
};
/**
* Sets the extra fields to keep from the parents
*/
config.extraFields = config.extraFields || [];
object.setExtraFields = function(newExtraFields) {
config.extraFields = newExtraFields;
return this;
};
/**
* Some default $http parameter to be used in EVERY call
**/
config.defaultHttpFields = config.defaultHttpFields || {};
object.setDefaultHttpFields = function(values) {
config.defaultHttpFields = values;
return this;
};
/**
* Always return plain data, no restangularized object
**/
config.plainByDefault = config.plainByDefault || false;
object.setPlainByDefault = function(value) {
config.plainByDefault = value === true ? true : false;
return this;
};
config.withHttpValues = function(httpLocalConfig, obj) {
return _.defaults(obj, httpLocalConfig, config.defaultHttpFields);
};
config.encodeIds = _.isUndefined(config.encodeIds) ? true : config.encodeIds;
object.setEncodeIds = function(encode) {
config.encodeIds = encode;
};
config.defaultRequestParams = config.defaultRequestParams || {
get: {},
post: {},
put: {},
remove: {},
common: {}
};
object.setDefaultRequestParams = function(param1, param2) {
var methods = [],
params = param2 || param1;
if (!_.isUndefined(param2)) {
if (_.isArray(param1)) {
methods = param1;
} else {
methods.push(param1);
}
} else {
methods.push('common');
}
_.each(methods, function(method) {
config.defaultRequestParams[method] = params;
});
return this;
};
object.requestParams = config.defaultRequestParams;
config.defaultHeaders = config.defaultHeaders || {};
object.setDefaultHeaders = function(headers) {
config.defaultHeaders = headers;
object.defaultHeaders = config.defaultHeaders;
return this;
};
object.defaultHeaders = config.defaultHeaders;
/**
* Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override
**/
config.methodOverriders = config.methodOverriders || [];
object.setMethodOverriders = function(values) {
var overriders = _.extend([], values);
if (config.isOverridenMethod('delete', overriders)) {
overriders.push('remove');
}
config.methodOverriders = overriders;
return this;
};
config.jsonp = _.isUndefined(config.jsonp) ? false : config.jsonp;
object.setJsonp = function(active) {
config.jsonp = active;
};
config.isOverridenMethod = function(method, values) {
var search = values || config.methodOverriders;
return !_.isUndefined(_.find(search, function(one) {
return one.toLowerCase() === method.toLowerCase();
}));
};
/**
* Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams
**/
config.urlCreator = config.urlCreator || 'path';
object.setUrlCreator = function(name) {
if (!_.has(config.urlCreatorFactory, name)) {
throw new Error('URL Path selected isn\'t valid');
}
config.urlCreator = name;
return this;
};
/**
* You can set the restangular fields here. The 3 required fields for Restangular are:
*
* id: Id of the element
* route: name of the route of this element
* parentResource: the reference to the parent resource
*
* All of this fields except for id, are handled (and created) by Restangular. By default,
* the field values will be id, route and parentResource respectively
*/
config.restangularFields = config.restangularFields || {
id: 'id',
route: 'route',
parentResource: 'parentResource',
restangularCollection: 'restangularCollection',
cannonicalId: '__cannonicalId',
etag: 'restangularEtag',
selfLink: 'href',
get: 'get',
getList: 'getList',
put: 'put',
post: 'post',
remove: 'remove',
head: 'head',
trace: 'trace',
options: 'options',
patch: 'patch',
getRestangularUrl: 'getRestangularUrl',
getRequestedUrl: 'getRequestedUrl',
putElement: 'putElement',
addRestangularMethod: 'addRestangularMethod',
getParentList: 'getParentList',
clone: 'clone',
ids: 'ids',
httpConfig: '_$httpConfig',
reqParams: 'reqParams',
one: 'one',
all: 'all',
several: 'several',
oneUrl: 'oneUrl',
allUrl: 'allUrl',
customPUT: 'customPUT',
customPATCH: 'customPATCH',
customPOST: 'customPOST',
customDELETE: 'customDELETE',
customGET: 'customGET',
customGETLIST: 'customGETLIST',
customOperation: 'customOperation',
doPUT: 'doPUT',
doPATCH: 'doPATCH',
doPOST: 'doPOST',
doDELETE: 'doDELETE',
doGET: 'doGET',
doGETLIST: 'doGETLIST',
fromServer: 'fromServer',
withConfig: 'withConfig',
withHttpConfig: 'withHttpConfig',
singleOne: 'singleOne',
plain: 'plain',
save: 'save',
restangularized: 'restangularized'
};
object.setRestangularFields = function(resFields) {
config.restangularFields =
_.extend(config.restangularFields, resFields);
return this;
};
config.isRestangularized = function(obj) {
return !!obj[config.restangularFields.restangularized];
};
config.setFieldToElem = function(field, elem, value) {
var properties = field.split('.');
var idValue = elem;
_.each(_.initial(properties), function(prop) {
idValue[prop] = {};
idValue = idValue[prop];
});
idValue[_.last(properties)] = value;
return this;
};
config.getFieldFromElem = function(field, elem) {
var properties = field.split('.');
var idValue = elem;
_.each(properties, function(prop) {
if (idValue) {
idValue = idValue[prop];
}
});
return angular.copy(idValue);
};
config.setIdToElem = function(elem, id /*, route */ ) {
config.setFieldToElem(config.restangularFields.id, elem, id);
return this;
};
config.getIdFromElem = function(elem) {
return config.getFieldFromElem(config.restangularFields.id, elem);
};
config.isValidId = function(elemId) {
return '' !== elemId && !_.isUndefined(elemId) && !_.isNull(elemId);
};
config.setUrlToElem = function(elem, url /*, route */ ) {
config.setFieldToElem(config.restangularFields.selfLink, elem, url);
return this;
};
config.getUrlFromElem = function(elem) {
return config.getFieldFromElem(config.restangularFields.selfLink, elem);
};
config.useCannonicalId = _.isUndefined(config.useCannonicalId) ? false : config.useCannonicalId;
object.setUseCannonicalId = function(value) {
config.useCannonicalId = value;
return this;
};
config.getCannonicalIdFromElem = function(elem) {
var cannonicalId = elem[config.restangularFields.cannonicalId];
var actualId = config.isValidId(cannonicalId) ? cannonicalId : config.getIdFromElem(elem);
return actualId;
};
/**
* Sets the Response parser. This is used in case your response isn't directly the data.
* For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}}
* you can extract this data which is the one that needs wrapping
*
* The ResponseExtractor is a function that receives the response and the method executed.
*/
config.responseInterceptors = config.responseInterceptors || [];
config.defaultResponseInterceptor = function(data /*, operation, what, url, response, deferred */ ) {
return data;
};
config.responseExtractor = function(data, operation, what, url, response, deferred) {
var interceptors = angular.copy(config.responseInterceptors);
interceptors.push(config.defaultResponseInterceptor);
var theData = data;
_.each(interceptors, function(interceptor) {
theData = interceptor(theData, operation,
what, url, response, deferred);
});
return theData;
};
object.addResponseInterceptor = function(extractor) {
config.responseInterceptors.push(extractor);
return this;
};
config.errorInterceptors = config.errorInterceptors || [];
object.addErrorInterceptor = function(interceptor) {
config.errorInterceptors.push(interceptor);
return this;
};
object.setResponseInterceptor = object.addResponseInterceptor;
object.setResponseExtractor = object.addResponseInterceptor;
object.setErrorInterceptor = object.addErrorInterceptor;
/**
* Response interceptor is called just before resolving promises.
*/
/**
* Request interceptor is called before sending an object to the server.
*/
config.requestInterceptors = config.requestInterceptors || [];
config.defaultInterceptor = function(element, operation, path, url, headers, params, httpConfig) {
return {
element: element,
headers: headers,
params: params,
httpConfig: httpConfig
};
};
config.fullRequestInterceptor = function(element, operation, path, url, headers, params, httpConfig) {
var interceptors = angular.copy(config.requestInterceptors);
var defaultRequest = config.defaultInterceptor(element, operation, path, url, headers, params, httpConfig);
return _.reduce(interceptors, function(request, interceptor) {
return _.extend(request, interceptor(request.element, operation,
path, url, request.headers, request.params, request.httpConfig));
}, defaultRequest);
};
object.addRequestInterceptor = function(interceptor) {
config.requestInterceptors.push(function(elem, operation, path, url, headers, params, httpConfig) {
return {
headers: headers,
params: params,
element: interceptor(elem, operation, path, url),
httpConfig: httpConfig
};
});
return this;
};
object.setRequestInterceptor = object.addRequestInterceptor;
object.addFullRequestInterceptor = function(interceptor) {
config.requestInterceptors.push(interceptor);
return this;
};
object.setFullRequestInterceptor = object.addFullRequestInterceptor;
config.onBeforeElemRestangularized = config.onBeforeElemRestangularized || function(elem) {
return elem;
};
object.setOnBeforeElemRestangularized = function(post) {
config.onBeforeElemRestangularized = post;
return this;
};
object.setRestangularizePromiseInterceptor = function(interceptor) {
config.restangularizePromiseInterceptor = interceptor;
return this;
};
/**
* This method is called after an element has been "Restangularized".
*
* It receives the element, a boolean indicating if it's an element or a collection
* and the name of the model
*
*/
config.onElemRestangularized = config.onElemRestangularized || function(elem) {
return elem;
};
object.setOnElemRestangularized = function(post) {
config.onElemRestangularized = post;
return this;
};
config.shouldSaveParent = config.shouldSaveParent || function() {
return true;
};
object.setParentless = function(values) {
if (_.isArray(values)) {
config.shouldSaveParent = function(route) {
return !_.includes(values, route);
};
} else if (_.isBoolean(values)) {
config.shouldSaveParent = function() {
return !values;
};
}
return this;
};
/**
* This lets you set a suffix to every request.
*
* For example, if your api requires that for JSon requests you do /users/123.json, you can set that
* in here.
*
*
* By default, the suffix is null
*/
config.suffix = _.isUndefined(config.suffix) ? null : config.suffix;
object.setRequestSuffix = function(newSuffix) {
config.suffix = newSuffix;
return this;
};
/**
* Add element transformers for certain routes.
*/
config.transformers = config.transformers || {};
config.matchTransformers = config.matchTransformers || [];
object.addElementTransformer = function(type, secondArg, thirdArg) {
var isCollection = null;
var transformer = null;
if (arguments.length === 2) {
transformer = secondArg;
} else {
transformer = thirdArg;
isCollection = secondArg;
}
var transformerFn = function(coll, elem) {
if (_.isNull(isCollection) || (coll === isCollection)) {
return transformer(elem);
}
return elem;
};
if (_.isRegExp(type)) {
config.matchTransformers.push({
regexp: type,
transformer: transformerFn
});
} else {
if (!config.transformers[type]) {
config.transformers[type] = [];
}
config.transformers[type].push(transformerFn);
}
return object;
};
object.extendCollection = function(route, fn) {
return object.addElementTransformer(route, true, fn);
};
object.extendModel = function(route, fn) {
return object.addElementTransformer(route, false, fn);
};
config.transformElem = function(elem, isCollection, route, Restangular, force) {
if (!force && !config.transformLocalElements && !elem[config.restangularFields.fromServer]) {
return elem;
}
var changedElem = elem;
var matchTransformers = config.matchTransformers;
if (matchTransformers) {
_.each(matchTransformers, function(transformer) {
if (transformer.regexp.test(route)) {
changedElem = transformer.transformer(isCollection, changedElem);
}
});
}
var typeTransformers = config.transformers[route];
if (typeTransformers) {
_.each(typeTransformers, function(transformer) {
changedElem = transformer(isCollection, changedElem);
});
}
return config.onElemRestangularized(changedElem, isCollection, route, Restangular);
};
config.transformLocalElements = _.isUndefined(config.transformLocalElements) ?
false :
config.transformLocalElements;
object.setTransformOnlyServerElements = function(active) {
config.transformLocalElements = !active;
};
config.fullResponse = _.isUndefined(config.fullResponse) ? false : config.fullResponse;
object.setFullResponse = function(full) {
config.fullResponse = full;
return this;
};
//Internal values and functions
config.urlCreatorFactory = {};
/**
* Base URL Creator. Base prototype for everything related to it
**/
var BaseCreator = function() {};
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();
};
function RestangularResource(config, $http, url, configurer) {
var resource = {};
_.each(_.keys(configurer), function(key) {
var value = configurer[key];
// Add default parameters
value.params = _.extend({}, value.params, config.defaultRequestParams[value.method.toLowerCase()]);
// We don't want the ? if no params are there
if (_.isEmpty(value.params)) {
delete value.params;
}
if (config.isSafe(value.method)) {
resource[key] = function() {
return $http(_.extend(value, {
url: url
}));
};
} else {
resource[key] = function(data) {
return $http(_.extend(value, {
url: url,
data: data
}));
};
}
});
return resource;
}
BaseCreator.prototype.resource = function(current, $http, localHttpConfig, callHeaders, callParams, what, etag, operation) {
var params = _.defaults(callParams || {}, this.config.defaultRequestParams.common);
var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders);
if (etag) {
if (!config.isSafe(operation)) {
headers['If-Match'] = etag;
} else {
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 RestangularResource(this.config, $http, url, {
getList: this.config.withHttpValues(localHttpConfig, {
method: 'GET',
params: params,
headers: headers
}),
get: this.config.withHttpValues(localHttpConfig, {
method: 'GET',
params: params,
headers: headers
}),
jsonp: this.config.withHttpValues(localHttpConfig, {
method: 'jsonp',
params: params,
headers: headers
}),
put: this.config.withHttpValues(localHttpConfig, {
method: 'PUT',
params: params,
headers: headers
}),
post: this.config.withHttpValues(localHttpConfig, {
method: 'POST',
params: params,
headers: headers
}),
remove: this.config.withHttpValues(localHttpConfig, {
method: 'DELETE',
params: params,
headers: headers
}),
head: this.config.withHttpValues(localHttpConfig, {
method: 'HEAD',
params: params,
headers: headers
}),
trace: this.config.withHttpValues(localHttpConfig, {
method: 'TRACE',
params: params,
headers: headers
}),
options: this.config.withHttpValues(localHttpConfig, {
method: 'OPTIONS',
params: params,
headers: headers
}),
patch: this.config.withHttpValues(localHttpConfig, {
method: 'PATCH',
params: params,
headers: headers
})
});
};
/**
* 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
**/
var Path = function() {};
Path.prototype = new BaseCreator();
Path.prototype.normalizeUrl = function(url) {
var parts = /((?:http[s]?:)?\/\/)?(.*)?/.exec(url);
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) {
elemId = __this.config.getCannonicalIdFromElem(elem);
} else {
elemId = __this.config.getIdFromElem(elem);
}
if (config.isValidId(elemId) && !elem.singleOne) {
elemUrl += '/' + (__this.config.encodeIds ? encodeURIComponent(elemId) : elemId);
}
}
}
acum = acum.replace(/\/$/, '') + '/' + elemUrl;
return __this.normalizeUrl(acum);
}, this.config.baseUrl);
};
Path.prototype.fetchUrl = function(current, what) {
var baseUrl = this.base(current);
if (what) {
baseUrl += '/' + what;
}
return baseUrl;
};
Path.prototype.fetchRequestedUrl = function(current, what) {
var url = this.fetchUrl(current, what);
var params = current[config.restangularFields.reqParams];
// From here on and until the end of fetchRequestedUrl,
// the code has been kindly borrowed from angular.js
// The reason for such code bloating is coherence:
// If the user were to use this for cache management, the
// serialization of parameters would need to be identical
// to the one done by angular for cache keys to match.
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for (var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
if (!params) {
return url + (this.config.suffix || '');
}
var parts = [];
forEachSorted(params, function(value, key) {
if (value === null || value === undefined) {
return;
}
if (!angular.isArray(value)) {
value = [value];
}
angular.forEach(value, function(v) {
if (angular.isObject(v)) {
v = angular.toJson(v);
}
parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v));
});
});
return url + (this.config.suffix || '') + ((url.indexOf('?') === -1) ? '?' : '&') + parts.join('&');
};
config.urlCreatorFactory.path = Path;
};
var globalConfiguration = {};
Configurer.init(this, globalConfiguration);
this.$get = ['$http', '$q', function($http, $q) {
function createServiceForConfiguration(config) {
var service = {};
var urlHandler = new config.urlCreatorFactory[config.urlCreator]();
urlHandler.setConfig(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);
}
}
// Elements
function stripRestangular(elem) {
if (_.isArray(elem)) {
var array = [];
_.each(elem, function(value) {
array.push(config.isRestangularized(value) ? stripRestangular(value) : value);
});
return array;
} else {
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(fetchFunction, elem);
elem[config.restangularFields.doGETLIST] = elem[config.restangularFields.customGETLIST];
}
function copyRestangularizedElement(element) {
var copiedElement = angular.copy(element);