-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathangularjs-rails-resource.js
1703 lines (1461 loc) · 80.2 KB
/
angularjs-rails-resource.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
/**
* A resource factory inspired by $resource from AngularJS
* @version v2.3.1 - 2021-07-26
* @link https://github.com/FineLinePrototyping/angularjs-rails-resource.git
* @author
*/
(function (undefined) {
angular.module('rails', ['ng']);
}());
(function (undefined) {
angular.module('rails').factory('RailsInflector', function() {
function camelize(key) {
if (!angular.isString(key)) {
return key;
}
// should this match more than word and digit characters?
return key.replace(/_[\w\d]/g, function (match, index, string) {
return index === 0 ? match : string.charAt(index + 1).toUpperCase();
});
}
function underscore(key) {
if (!angular.isString(key)) {
return key;
}
// TODO match the latest logic from Active Support
return key.replace(/[A-Z]/g, function (match, index) {
return index === 0 ? match : '_' + match.toLowerCase();
});
}
function pluralize(value) {
// TODO match Active Support
return value + 's';
}
return {
camelize: camelize,
underscore: underscore,
pluralize: pluralize
};
});
}());
(function (undefined) {
angular.module('rails').factory('RailsResourceInjector', ['$injector', function($injector) {
/**
* Allow dependencies to be referenced by name or instance. If referenced by name AngularJS $injector
* is used to retrieve the dependency.
*
* @param dependency (string | function) The dependency to retrieve
* @returns {*} The dependency
*/
function getDependency(dependency) {
if (dependency) {
return angular.isString(dependency) ? $injector.get(dependency) : dependency;
}
return undefined;
}
/**
* Looks up and instantiates an instance of the requested service. If the service is not a string then it is
* assumed to be a constructor function.
*
* @param {String|function|Object} service The service to instantiate
* @returns {*} A new instance of the requested service
*/
function createService(service) {
if (service) {
return $injector.instantiate(getDependency(service));
}
return undefined;
}
/**
* Looks up and instantiates an instance of the requested service if .
* @param {String|function|Object} service The service to instantiate
* @returns {*}
*/
function getService(service) {
// strings and functions are not considered objects by angular.isObject()
if (angular.isObject(service)) {
return service;
} else if (service) {
return createService(service);
}
return undefined;
}
return {
createService: createService,
getService: getService,
getDependency: getDependency
};
}]);
}());
/**
* @ngdoc function
* @name rails.railsUrlBuilder
* @function
* @requires $interpolate
*
* @description
*
* Compiles a URL template string into an interpolation function using $interpolate. If no interpolation bindings
* found then {{id}} is appended to the url string.
*
<pre>
expect(railsUrlBuilder('/books')()).toEqual('/books')
expect(railsUrlBuilder('/books')({id: 1})).toEqual('/books/1')
expect(railsUrlBuilder('/authors/{{authorId}}/books/{{id}}')({id: 1, authorId: 2})).toEqual('/authors/2/books/1')
</pre>
*
* If the $interpolate startSymbol and endSymbol have been customized those values should be used instead of {{ and }}
*
* @param {string|function} url If the url is a function then that function is returned. Otherwise the url string
* is passed to $interpolate as an expression.
*
* @returns {function(context)} As stated by $interpolate documentation:
* An interpolation function which is used to compute the interpolated
* string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against.
*
*/
(function (undefined) {
angular.module('rails').factory('railsUrlBuilder', ['$interpolate', function($interpolate) {
return function (config) {
var url = config.url,
idAttribute = config.idAttribute,
expression;
if (angular.isFunction(url) || angular.isUndefined(url)) {
return url;
}
if (!config.singular && url.indexOf($interpolate.startSymbol()) === -1) {
url = url + '/' + $interpolate.startSymbol() + idAttribute + $interpolate.endSymbol();
}
expression = $interpolate(url);
return function (params) {
url = expression(params);
if (url.charAt(url.length - 1) === '/') {
url = url.substr(0, url.length - 1);
}
return url;
};
};
}]);
}());
(function (undefined) {
angular.module('rails').provider('railsSerializer', function() {
var defaultOptions = {
underscore: undefined,
camelize: undefined,
pluralize: undefined,
exclusionMatchers: []
};
/**
* Configures the underscore method used by the serializer. If not defined then <code>RailsInflector.underscore</code>
* will be used.
*
* @param {function(string):string} fn The function to use for underscore conversion
* @returns {railsSerializerProvider} The provider for chaining
*/
this.underscore = function(fn) {
defaultOptions.underscore = fn;
return this;
};
/**
* Configures the camelize method used by the serializer. If not defined then <code>RailsInflector.camelize</code>
* will be used.
*
* @param {function(string):string} fn The function to use for camelize conversion
* @returns {railsSerializerProvider} The provider for chaining
*/
this.camelize = function(fn) {
defaultOptions.camelize = fn;
return this;
};
/**
* Configures the pluralize method used by the serializer. If not defined then <code>RailsInflector.pluralize</code>
* will be used.
*
* @param {function(string):string} fn The function to use for pluralizing strings.
* @returns {railsSerializerProvider} The provider for chaining
*/
this.pluralize = function(fn) {
defaultOptions.pluralize = fn;
return this;
};
/**
* Configures the array exclusion matchers by the serializer. Exclusion matchers can be one of the following:
* * string - Defines a prefix that is used to test for exclusion
* * RegExp - A custom regular expression that is tested against the attribute name
* * function - A custom function that accepts a string argument and returns a boolean with true indicating exclusion.
*
* @param {Array.<string|function(string):boolean|RegExp} exclusions An array of exclusion matchers
* @returns {railsSerializerProvider} The provider for chaining
*/
this.exclusionMatchers = function(exclusions) {
defaultOptions.exclusionMatchers = exclusions;
return this;
};
this.$get = ['$injector', 'RailsInflector', 'RailsResourceInjector', function ($injector, RailsInflector, RailsResourceInjector) {
defaultOptions.underscore = defaultOptions.underscore || RailsInflector.underscore;
defaultOptions.camelize = defaultOptions.camelize || RailsInflector.camelize;
defaultOptions.pluralize = defaultOptions.pluralize || RailsInflector.pluralize;
function railsSerializer(options, customizer) {
function Serializer() {
if (angular.isFunction(options)) {
customizer = options;
options = {};
}
this.exclusions = {};
this.inclusions = {};
this.serializeMappings = {};
this.deserializeMappings = {};
this.customSerializedAttributes = {};
this.preservedAttributes = {};
this.customSerializers = {};
this.nestedResources = {};
this.polymorphics = {};
this.options = angular.extend({excludeByDefault: false}, defaultOptions, options || {});
if (customizer) {
customizer.call(this, this);
}
}
/**
* Accepts a variable list of attribute names to exclude from JSON serialization.
*
* @param attributeNames... {string} Variable number of attribute name parameters
* @returns {Serializer} this for chaining support
*/
Serializer.prototype.exclude = function () {
var exclusions = this.exclusions;
angular.forEach(arguments, function (attributeName) {
exclusions[attributeName] = false;
});
return this;
};
/**
* Accepts a variable list of attribute names that should be included in JSON serialization.
* Using this method will by default exclude all other attributes and only the ones explicitly included using <code>only</code> will be serialized.
* @param attributeNames... {string} Variable number of attribute name parameters
* @returns {Serializer} this for chaining support
*/
Serializer.prototype.only = function () {
var inclusions = this.inclusions;
this.options.excludeByDefault = true;
angular.forEach(arguments, function (attributeName) {
inclusions[attributeName] = true;
});
return this;
};
/**
* This is a shortcut for rename that allows you to specify a variable number of attributes that should all be renamed to
* <code>{attributeName}_attributes</code> to work with the Rails nested_attributes feature.
* @param attributeNames... {string} Variable number of attribute name parameters
* @returns {Serializer} this for chaining support
*/
Serializer.prototype.nestedAttribute = function () {
var self = this;
angular.forEach(arguments, function (attributeName) {
self.rename(attributeName, attributeName + '_attributes');
});
return this;
};
/**
* Specifies an attribute that is a nested resource within the parent object.
* Nested resources do not imply nested attributes, if you want both you still have to specify call <code>nestedAttribute</code> as well.
*
* A nested resource serves two purposes. First, it defines the resource that should be used when constructing resources from the server.
* Second, it specifies how the nested object should be serialized.
*
* An optional third parameter <code>serializer</code> is available to override the serialization logic
* of the resource in case you need to serialize it differently in multiple contexts.
*
* @param attributeName {string} The name of the attribute that is a nested resource
* @param resource {string | Resource} A reference to the resource that the attribute is a type of.
* @param serializer {string | Serializer} (optional) An optional serializer reference to override the nested resource's default serializer
* @returns {Serializer} this for chaining support
*/
Serializer.prototype.resource = function (attributeName, resource, serializer) {
this.nestedResources[attributeName] = resource;
if (serializer) {
this.serializeWith(attributeName, serializer);
}
return this;
};
/**
* Specifies a polymorphic association according to Rails' standards.
* Polymorphic associations have a <code>{name}_id</code> and <code>{name}_type</code> columns in the database.
*
* The <code>{name}_type</code> attribute will specify which resource will be used to serialize and deserialize the data.
*
* @param names... {string} Variable number of name parameters
* @returns {Serializer} this for chaining support
*/
Serializer.prototype.polymorphic = function () {
var polymorphics = this.polymorphics;
angular.forEach(arguments, function(attributeName) {
polymorphics[attributeName] = true;
});
return this;
};
/**
* Specifies a custom name mapping for an attribute.
* On serializing to JSON the jsonName will be used.
* On deserialization, if jsonName is seen then it will be renamed as javascriptName in the resulting resource.
*
* @param javascriptName {string} The attribute name as it appears in the JavaScript object
* @param jsonName {string} The attribute name as it should appear in JSON
* @param bidirectional {boolean} (optional) Allows turning off the bidirectional renaming, defaults to true.
* @returns {Serializer} this for chaining support
*/
Serializer.prototype.rename = function (javascriptName, jsonName, bidirectional) {
this.serializeMappings[javascriptName] = jsonName;
if (bidirectional || bidirectional === undefined) {
this.deserializeMappings[jsonName] = javascriptName;
}
return this;
};
/**
* Allows custom attribute creation as part of the serialization to JSON.
*
* @param attributeName {string} The name of the attribute to add
* @param value {*} The value to add, if specified as a function then the function will be called during serialization
* and should return the value to add.
* @returns {Serializer} this for chaining support
*/
Serializer.prototype.add = function (attributeName, value) {
this.customSerializedAttributes[attributeName] = value;
return this;
};
/**
* Allows the attribute to be preserved unmodified in the resulting object.
*
* @param attributeName {string} The name of the attribute to add
* @returns {Serializer} this for chaining support
*/
Serializer.prototype.preserve = function(attributeName) {
this.preservedAttributes[attributeName] = true;
return this;
};
/**
* Specify a custom serializer to use for an attribute.
*
* @param attributeName {string} The name of the attribute
* @param serializer {string | function} A reference to the custom serializer to use for the attribute.
* @returns {Serializer} this for chaining support
*/
Serializer.prototype.serializeWith = function (attributeName, serializer) {
this.customSerializers[attributeName] = serializer;
return this;
};
/**
* Determines whether or not an attribute should be excluded.
*
* If the option excludeByDefault has been set then attributes will default to excluded and will only
* be included if they have been included using the "only" customization function.
*
* If the option excludeByDefault has not been set then attributes must be explicitly excluded using the "exclude"
* customization function or must be matched by one of the exclusionMatchers.
*
* @param attributeName The name of the attribute to check for exclusion
* @returns {boolean} true if excluded, false otherwise
*/
Serializer.prototype.isExcludedFromSerialization = function (attributeName) {
if ((this.options.excludeByDefault && !this.inclusions.hasOwnProperty(attributeName)) || this.exclusions.hasOwnProperty(attributeName)) {
return true;
}
if (this.options.exclusionMatchers) {
var excluded = false;
angular.forEach(this.options.exclusionMatchers, function (matcher) {
if (angular.isString(matcher)) {
excluded = excluded || attributeName.indexOf(matcher) === 0;
} else if (angular.isFunction(matcher)) {
excluded = excluded || matcher.call(undefined, attributeName);
} else if (matcher instanceof RegExp) {
excluded = excluded || matcher.test(attributeName);
}
});
return excluded;
}
return false;
};
/**
* Remaps the attribute name to the serialized form which includes:
* - checking for exclusion
* - remapping to a custom value specified by the rename customization function
* - underscoring the name
*
* @param attributeName The current attribute name
* @returns {*} undefined if the attribute should be excluded or the mapped attribute name
*/
Serializer.prototype.getSerializedAttributeName = function (attributeName) {
var mappedName = this.serializeMappings[attributeName] || attributeName;
var mappedNameExcluded = this.isExcludedFromSerialization(mappedName),
attributeNameExcluded = this.isExcludedFromSerialization(attributeName);
if(this.options.excludeByDefault) {
if(mappedNameExcluded && attributeNameExcluded) {
return undefined;
}
} else {
if (mappedNameExcluded || attributeNameExcluded) {
return undefined;
}
}
return this.underscore(mappedName);
};
/**
* Determines whether or not an attribute should be excluded from deserialization.
*
* By default, we do not exclude any attributes from deserialization.
*
* @param attributeName The name of the attribute to check for exclusion
* @returns {boolean} true if excluded, false otherwise
*/
Serializer.prototype.isExcludedFromDeserialization = function (attributeName) {
return false;
};
/**
* Remaps the attribute name to the deserialized form which includes:
* - camelizing the name
* - checking for exclusion
* - remapping to a custom value specified by the rename customization function
*
* @param attributeName The current attribute name
* @returns {*} undefined if the attribute should be excluded or the mapped attribute name
*/
Serializer.prototype.getDeserializedAttributeName = function (attributeName) {
var camelizedName = this.camelize(attributeName);
camelizedName = this.deserializeMappings[attributeName] ||
this.deserializeMappings[camelizedName] ||
camelizedName;
if (this.isExcludedFromDeserialization(attributeName) || this.isExcludedFromDeserialization(camelizedName)) {
return undefined;
}
return camelizedName;
};
/**
* Returns a reference to the nested resource that has been specified for the attribute.
* @param attributeName The attribute name
* @param data the entire object being serialized
* @returns {*} undefined if no nested resource has been specified or a reference to the nested resource class
*/
Serializer.prototype.getNestedResource = function (attributeName, data) {
var resourceName;
if (!this.polymorphics[attributeName]) {
resourceName = this.nestedResources[attributeName];
} else {
resourceName = data[attributeName + '_type'];
}
return RailsResourceInjector.getDependency(resourceName);
};
/**
* Returns a custom serializer for the attribute if one has been specified. Custom serializers can be specified
* in one of two ways. The serializeWith customization method allows specifying a custom serializer for any attribute.
* Or an attribute could have been specified as a nested resource in which case the nested resource's serializer
* is used. Custom serializers specified using serializeWith take precedence over the nested resource serializer.
*
* @param attributeName The attribute name
* @param data the entire object being serialized
* @returns {*} undefined if no custom serializer has been specified or an instance of the Serializer
*/
Serializer.prototype.getAttributeSerializer = function (attributeName, data) {
var resource = this.getNestedResource(attributeName, data),
serializer = this.customSerializers[attributeName];
// custom serializer takes precedence over resource serializer
if (serializer) {
return RailsResourceInjector.createService(serializer);
} else if (resource) {
return resource.config.serializer;
}
return undefined;
};
/**
* Prepares the data for serialization to JSON.
*
* @param data The data to prepare
* @returns {*} A new object or array that is ready for JSON serialization
*/
Serializer.prototype.serializeData = function (data) {
var result = data,
self = this;
if (angular.isArray(data)) {
result = [];
angular.forEach(data, function (value) {
result.push(self.serializeData(value));
});
} else if (angular.isObject(data)) {
if (angular.isDate(data)) {
return data;
}
result = {};
this.serializeObject(result, data);
}
return result;
};
Serializer.prototype.serializeObject = function(result, data) {
var tthis = this;
angular.forEach(data, function (value, key) {
// if the value is a function then it can't be serialized to JSON so we'll just skip it
if (!angular.isFunction(value)) {
tthis.serializeAttribute(result, key, value, data);
}
});
return data;
};
/**
* Transforms an attribute and its value and stores it on the parent data object. The attribute will be
* renamed as needed and the value itself will be serialized as well.
*
* @param result The object that the attribute will be added to
* @param attribute The attribute to transform
* @param value The current value of the attribute
* @param data the entire object being serialized
*/
Serializer.prototype.serializeAttribute = function (result, attribute, value, data) {
var serializer = this.getAttributeSerializer(attribute, data),
serializedAttributeName = this.getSerializedAttributeName(attribute);
// undefined means the attribute should be excluded from serialization
if (serializedAttributeName === undefined) {
return;
}
result[serializedAttributeName] = serializer ? serializer.serialize(value) : this.serializeData(value);
};
/**
* Serializes the data by applying various transformations such as:
* - Underscoring attribute names
* - attribute renaming
* - attribute exclusion
* - custom attribute addition
*
* @param data The data to prepare
* @returns {*} A new object or array that is ready for JSON serialization
*/
Serializer.prototype.serialize = function (data) {
var result = angular.copy(data),
self = this;
if (angular.isObject(result)) {
angular.forEach(this.customSerializedAttributes, function (value, key) {
if (angular.isArray(result)) {
angular.forEach(result, function (item, index) {
var itemValue = value;
if (angular.isFunction(value)) {
itemValue = itemValue.call(item, item);
}
self.serializeAttribute(item, key, itemValue, data);
});
} else {
if (angular.isFunction(value)) {
value = value.call(data, data);
}
self.serializeAttribute(result, key, value, data);
}
});
}
result = this.serializeData(result);
return result;
};
/**
* Iterates over the data deserializing each entry on arrays and each key/value on objects.
*
* @param data The object to deserialize
* @param Resource (optional) The resource type to deserialize the result into
* @param triggerPhase (optional) Whether to trigger the afterDeserialize phase
* @returns {*} A new object or an instance of Resource populated with deserialized data.
*/
Serializer.prototype.deserializeData = function (data, Resource, triggerPhase) {
var result = data,
self = this;
if (angular.isArray(data)) {
result = [];
angular.forEach(data, function (value) {
result.push(self.deserializeData(value, Resource, triggerPhase));
});
} else if (angular.isObject(data)) {
if (angular.isDate(data)) {
return data;
}
result = {};
if (Resource) {
result = new Resource.config.resourceConstructor();
}
this.deserializeObject(result, data, triggerPhase);
}
return result;
};
Serializer.prototype.deserializeObject = function (result, data, triggerPhase) {
var tthis = this;
angular.forEach(data, function (value, key) {
tthis.deserializeAttribute(result, key, value, data);
});
if (triggerPhase && result.constructor.runInterceptorPhase) {
result.constructor.runInterceptorPhase('afterDeserialize', result);
}
return data;
};
/**
* Transforms an attribute and its value and stores it on the parent data object. The attribute will be
* renamed as needed and the value itself will be deserialized as well.
*
* @param result The object that the attribute will be added to
* @param attribute The attribute to transform
* @param value The current value of the attribute
* @param data the entire object being deserialized
*/
Serializer.prototype.deserializeAttribute = function (result, attribute, value, data) {
var serializer,
NestedResource,
attributeName = this.getDeserializedAttributeName(attribute);
// undefined means the attribute should be excluded from serialization
if (attributeName === undefined) {
return;
}
serializer = this.getAttributeSerializer(attributeName, data);
NestedResource = this.getNestedResource(attributeName, data);
// preserved attributes are assigned unmodified
if (this.preservedAttributes[attributeName]) {
result[attributeName] = value;
} else {
result[attributeName] = serializer ? serializer.deserialize(value, NestedResource, true) : this.deserializeData(value, NestedResource, true);
}
};
/**
* Deserializes the data by applying various transformations such as:
* - Camelizing attribute names
* - attribute renaming
* - attribute exclusion
* - nested resource creation
*
* @param data The object to deserialize
* @param Resource (optional) The resource type to deserialize the result into
* @param triggerPhase (optional) Whether to trigger the afterDeserialize phase
* @returns {*} A new object or an instance of Resource populated with deserialized data
*/
Serializer.prototype.deserialize = function (data, Resource, triggerPhase) {
// just calls deserializeValue for now so we can more easily add on custom attribute logic for deserialize too
return this.deserializeData(data, Resource, triggerPhase);
};
Serializer.prototype.pluralize = function (value) {
if (this.options.pluralize) {
return this.options.pluralize(value);
}
return value;
};
Serializer.prototype.underscore = function (value) {
if (this.options.underscore) {
return this.options.underscore(value);
}
return value;
};
Serializer.prototype.camelize = function (value) {
if (this.options.camelize) {
return this.options.camelize(value);
}
return value;
};
return Serializer;
}
railsSerializer.defaultOptions = defaultOptions;
return railsSerializer;
}];
});
}());
(function (undefined) {
angular.module('rails').factory('railsRootWrapper', function () {
return {
wrap: function (data, resource) {
var result = {};
result[angular.isArray(data) ? resource.config.pluralName : resource.config.name] = data;
return result;
},
unwrap: function (response, resource, isObject) {
if (response.data && response.data.hasOwnProperty(resource.config.name)) {
response.data = response.data[resource.config.name];
} else if (response.data && response.data.hasOwnProperty(resource.config.pluralName) && !isObject) {
response.data = response.data[resource.config.pluralName];
}
return response;
}
};
});
angular.module('rails').provider('RailsResource', function () {
var defaultOptions = {
rootWrapping: true,
updateMethod: 'put',
httpConfig: {},
defaultParams: undefined,
underscoreParams: true,
fullResponse: false,
singular: false,
extensions: []
};
/**
* Enables or disables root wrapping by default for RailsResources
* Defaults to true.
* @param {boolean} value true to enable root wrapping, false to disable
* @returns {RailsResourceProvider} The provider instance
*/
this.rootWrapping = function (value) {
defaultOptions.rootWrapping = value;
return this;
};
/**
* Configures what HTTP operation should be used for update by default for RailsResources.
* Defaults to 'put'
* @param value
* @returns {RailsResourceProvider} The provider instance
*/
this.updateMethod = function (value) {
defaultOptions.updateMethod = value;
return this;
};
/**
* Configures default HTTP configuration operations for all RailsResources.
*
* @param {Object} value See $http for available configuration options.
* @returns {RailsResourceProvider} The provider instance
*/
this.httpConfig = function (value) {
defaultOptions.httpConfig = value;
return this;
};
/**
* Configures default HTTP query parameters for all RailsResources.
*
* @param {Object} value Object of key/value pairs representing the HTTP query parameters for all HTTP operations.
* @returns {RailsResourceProvider} The provider instance
*/
this.defaultParams = function (value) {
defaultOptions.defaultParams = value;
return this;
};
/**
* Configures whether or not underscore query parameters
* @param {boolean} value true to underscore. Defaults to true.
* @returns {RailsResourceProvider} The provider instance
*/
this.underscoreParams = function (value) {
defaultOptions.underscoreParams = value;
return this;
};
/**
* Configures whether the full response from $http is returned or just the result data.
* @param {boolean} value true to return full $http response. Defaults to false.
* @returns {RailsResourceProvider} The provider instance
*/
this.fullResponse = function (value) {
defaultOptions.fullResponse = value;
return this;
};
/**
* List of RailsResource extensions to include by default.
*
* @param {...string} extensions One or more extension names to include
* @returns {*}
*/
this.extensions = function () {
defaultOptions.extensions = [];
angular.forEach(arguments, function (value) {
defaultOptions.extensions = defaultOptions.extensions.concat(value);
});
return this;
};
this.$get = ['$http', '$q', '$timeout', 'railsUrlBuilder', 'railsSerializer', 'railsRootWrapper', 'RailsResourceInjector',
function ($http, $q, $timeout, railsUrlBuilder, railsSerializer, railsRootWrapper, RailsResourceInjector) {
function RailsResource(value) {
if (value) {
var response = this.constructor.deserialize({data: value});
if (this.constructor.config.rootWrapping) {
response = railsRootWrapper.unwrap(response, this.constructor, true);
}
angular.extend(this, response.data);
this.constructor.runInterceptorPhase('afterDeserialize', this);
}
}
/**
* Extends the RailsResource to the child constructor function making the child constructor a subclass of
* RailsResource. This is modeled off of CoffeeScript's class extend function. All RailsResource
* class properties defined are copied to the child class and the child's prototype chain is configured
* to allow instances of the child class to have all of the instance methods of RailsResource.
*
* Like CoffeeScript, a __super__ property is set on the child class to the parent resource's prototype chain.
* This is done to allow subclasses to extend the functionality of instance methods and still
* call back to the original method using:
*
* Class.__super__.method.apply(this, arguments);
*
* @param {function} child Child constructor function
* @returns {function} Child constructor function
*/
RailsResource.extendTo = function (child) {
angular.forEach(this, function (value, key) {
child[key] = value;
});
if (angular.isArray(this.$modules)) {
child.$modules = this.$modules.slice(0);
}
function ctor() {
this.constructor = child;
}
ctor.prototype = this.prototype;
child.prototype = new ctor();
child.__super__ = this.prototype;
return child;
};
/**
* Copies a mixin's properties to the resource.
*
* If module is a String then we it will be loaded using Angular's dependency injection. If the name is
* not valid then Angular will throw an error.
*
* @param {...String|function|Object} mixins The mixin or name of the mixin to add.
* @returns {RailsResource} this
*/
RailsResource.extend = function () {
angular.forEach(arguments, function (mixin) {
addMixin(this, this, mixin, function (Resource, mixin) {
if (angular.isFunction(mixin.extended)) {
mixin.extended(Resource);
}
});
}, this);
return this;
};
/**
* Copies a mixin's properties to the resource's prototype chain.
*
* If module is a String then we it will be loaded using Angular's dependency injection. If the name is
* not valid then Angular will throw an error.
*
* @param {...String|function|Object} mixins The mixin or name of the mixin to add
* @returns {RailsResource} this
*/
RailsResource.include = function () {
angular.forEach(arguments, function (mixin) {
addMixin(this, this.prototype, mixin, function (Resource, mixin) {
if (angular.isFunction(mixin.included)) {
mixin.included(Resource);
}
});
}, this);
return this;
};
/**
* Sets configuration options. This method may be called multiple times to set additional options or to
* override previous values (such as the case with inherited resources).
* @param cfg
*/
RailsResource.configure = function (cfg) {
cfg = cfg || {};
if (this.config) {
cfg = angular.extend({}, this.config, cfg);
}
this.config = {};
this.config.idAttribute = cfg.idAttribute || 'id';
this.config.url = cfg.url;
this.config.rootWrapping = booleanParam(cfg.rootWrapping, defaultOptions.rootWrapping); // using undefined check because config.rootWrapping || true would be true when config.rootWrapping === false
this.config.httpConfig = cfg.httpConfig || defaultOptions.httpConfig;
this.config.httpConfig.headers = angular.extend({'Accept': 'application/json', 'Content-Type': 'application/json'}, this.config.httpConfig.headers || {});
this.config.defaultParams = cfg.defaultParams || defaultOptions.defaultParams;
this.config.underscoreParams = booleanParam(cfg.underscoreParams, defaultOptions.underscoreParams);
this.config.updateMethod = (cfg.updateMethod || defaultOptions.updateMethod).toLowerCase();
this.config.fullResponse = booleanParam(cfg.fullResponse, defaultOptions.fullResponse);
this.config.singular = cfg.singular || defaultOptions.singular;
this.config.requestTransformers = cfg.requestTransformers ? cfg.requestTransformers.slice(0) : [];
this.config.responseInterceptors = cfg.responseInterceptors ? cfg.responseInterceptors.slice(0) : [];
this.config.afterResponseInterceptors = cfg.afterResponseInterceptors ? cfg.afterResponseInterceptors.slice(0) : [];
this.config.interceptors = cfg.interceptors ? cfg.interceptors.slice(0) : [];
this.config.serializer = RailsResourceInjector.getService(cfg.serializer || railsSerializer());