forked from platanus/angular-restmod
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathangular-restmod.js
More file actions
2614 lines (2364 loc) · 78.7 KB
/
Copy pathangular-restmod.js
File metadata and controls
2614 lines (2364 loc) · 78.7 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
/**
* API Bound Models for AngularJS
* @version v0.15.0 - 2014-07-21
* @link https://github.com/angular-platanus/restmod
* @author Ignacio Baixas <[email protected]>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function(angular, undefined) {
'use strict';
// Preload some angular stuff
var RMModule = angular.module('plRestmod', ['ng', 'platanus.inflector']);
/**
* @class $restmodProvider
*
* @description
*
* The $restmodProvider exposes $restmod configuration methods
*/
RMModule.provider('$restmod', [function() {
var BASE_CHAIN = []; // The base mixin chain
return {
/**
* @memberof $restmodProvider#
*
* @description
*
* Adds base mixins for every generated model.
*
* **ATTENTION** Model names should NOT be added to this chain.
*
* Base model chain is by default empty, all mixins added to the chain are
* prepended to every generated model.
*
* Usage:
*
* ```javascript
* $provider.pushModelBase('ChangeModel', 'LazyRelations', 'ThrottledModel')
* ```
*/
pushModelBase: function(/* _mix_names */) {
Array.prototype.push.apply(BASE_CHAIN, arguments);
return this;
},
/**
* @class $restmod
*
* @description
*
* The restmod service provides factory methods for the different restmod consumables.
*/
$get: ['RMModelFactory', 'RMBuilder', function(factory, Builder) {
var arraySlice = Array.prototype.slice;
var restmod = {
/**
* @memberOf $restmod#
*
* @description
*
* The model factory is used to generate new $restmod model types. It's recommended to put models inside factories,
* this is usefull later when defining relations and inheritance, since the angular $injector is used by
* these features. It's also the angular way of doing things.
*
* A simple model can be built like this:
*
* ```javascript
* angular.module('bike-app').factory('Bike', function($restmod) {
* return $restmod.model('/bikes');
* });
*```
*
* The `_url` parameter is the resource url the generated model will be bound to, if `null` is given then
* the model is *anonymous* and can only be used in another model context.
*
* The model also accepts one or more definition providers as one or more arguments after the _url parameter,
* posible definition providers are:
*
* * A definition object (more on this at the {@link BuilderApi}):
*
* ```javascript
* $restmod.model('/bikes', {
* viewed: { init: false },
* parts: { hasMany: 'Part' },
* '~afterCreate': function() {
* alert('Bike created!!');
* }
* });
*```
*
* * A definition function (more on this at the {@link BuilderApi}):
*
* ```javascript
* $restmod.model('/bikes', function() {
* this.attrDefault('viewed', false);
* this.attrMask('id', 'CU');
* });
*```
*
* * A mixin (generated using the mixin method) or model factory name:
*
* ```javascript
* $restmod.model('/bikes', 'BaseModel', 'PagedModel');
*```
*
* * A mixin (generated using the mixin method) or model object:
*
* ```javascript
* $restmod.model('/bikes', BaseModel, PagedModel);
* ```
*
* @param {string} _url Resource url.
* @param {mixed} _mix One or more mixins, description objects or description blocks.
* @return {StaticApi} The new model.
*/
model: function(_baseUrl/* , _mix */) {
// Generate a new model type.
var Model = factory(_baseUrl);
// Load builder and execute it.
var builder = new Builder(Model);
builder.loadMixinChain(BASE_CHAIN);
builder.loadMixinChain(Model.$chain = arraySlice.call(arguments, 1));
return Model;
},
/**
* @memberOf $restmod#
*
* @description
*
* The mixin factory is used to pack model behaviors without the overload of generating a new
* model. The mixin can then be passed as argument to a call to {@link $restmod#model#model}
* to extend the model capabilities.
*
* A mixin can also be passed to the {@link $restmodProvider#pushModelBase} method to provide
* a base behavior for all generated models.
*
* @param {mixed} _mix One or more mixins, description objects or description blocks.
* @return {object} The mixin
*/
mixin: function(/* _mix */) {
return { $isAbstract: true, $chain: arraySlice.call(arguments, 0) };
},
/**
* @memberOf $restmod#
*
* @description
*
* Shorcut method used to create singleton resources.
*
* Same as calling `$restmod.model(null).$single(_url)`
*
* Check the {@link StaticApi#$single} documentation for more information.
*
* @param {string} _url Resource url,
* @param {mixed} _mix Mixin chain.
* @return {RecordApi} New resource instance.
*/
singleton: function(_url/*, _mix */) {
return restmod.model.apply(this, arguments).$single(_url);
}
};
return restmod;
}]
};
}])
.factory('model', ['$restmod', function($restmod) {
return $restmod.model;
}])
.factory('mixin', ['$restmod', function($restmod) {
return $restmod.mixin;
}]);
RMModule.factory('RMBuilder', ['$injector', '$parse', '$filter', '$inflector', 'RMUtils', function($injector, $parse, $filter, $inflector, Utils) {
// TODO: add urlPrefix option
var forEach = angular.forEach,
bind = angular.bind,
isObject = angular.isObject,
isArray = angular.isArray,
isFunction = angular.isFunction;
/**
* @class BuilderApi
*
* @description
*
* Provides the DSL for model generation, it supports to modes of model definitions:
*
* ## Definition object
*
* This is the preferred way of describing a model behavior.
*
* A model description object looks like this:
*
* ```javascript
* $restmod.model('', {
*
* // ATTRIBUTE MODIFIERS
*
* propWithDefault: { init: 20 },
* propWithDecoder: { decode: 'date', chain: true },
*
* // RELATIONS
*
* hasManyRelation: { hasMany: 'Other' },
* hasOneRelation: { hasOne: 'Other' }
*
* // METHODS
*
* '@classMethod': function() {
* },
*
* instanceMethod: function() {
* },
*
* // HOOKS
*
* '~afterCreate': function() {
* }
* });
* ```
*
* With the exception of properties starting with a special character (**@** or **~**),
* each property in the definition object asigns a behavior to the same named property
* in a model's record.
*
* To modify a property behavior assign an object with the desired modifiers to a
* definition property with the same name. Builtin modifiers are:
*
* The following built in property modifiers are provided (see each mapped-method docs for usage information):
*
* * `init` sets an attribute default value, see {@link BuilderApi#attrDefault}
* * `mask` and `ignore` sets an attribute mask, see {@link BuilderApi#attrMask}
* * `decode` sets how an attribute is decoded after being fetch, maps to {@link BuilderApi#attrDecoder}
* * `encode` sets how an attribute is encoded before being sent, maps to {@link BuilderApi#attrEncoder}
* * `serialize` sets the encoder and decoder beaviour for an attribute, maps to {@link BuilderApi#attrSerializer}
* * `hasMany` sets a one to many hierarchical relation under the attribute name, maps to {@link BuilderApi#attrAsCollection}
* * `hasOne` sets a one to one hierarchical relation under the attribute name, maps to {@link BuilderApi#attrAsResource}
* * `belongsTo` sets a one to one reference relation under the attribute name, maps to {@link BuilderApi#attrAsReference}
*
* To add/override methods from the record api, a function can be passed to one of the
* description properties:
*
* ```javascript
* var Model = $restmod.model('/', {
* sayHello: function() { alert('hello!'); }
* })
*
* // then say hello is available for use at model records
* Model.$new().sayHello();
* ```
*
* If other kind of value (different from object or function) is passed to a definition property,
* then it is considered to be a default value. (same as calling {@link BuilderApi#define} at a definition function)
*
* ```javascript
* var Model = $restmod.model('/', {
* im20: 20 // same as { init: 20 }
* })
*
* // then say hello is available for use at model records
* Model.$new().im20; // 20
* ```
*
* To add static/collection methods to the Model, prefix the definition property name with **@**
* (same as calling {@link BuilderApi#classDefine} at a definition function).
*
* ```javascript
* var Model = $restmod.model('/', {
* '@sayHello': function() { alert('hello!'); }
* })
*
* // then say hello is available for use at model type and collection.
* Model.sayHello();
* Model.$collection().sayHello();
* ```
*
* To add hooks to the Model lifecycle events, prefix the definition property name with **~** and make sure the
* property name matches the event name (same as calling {@link BuilderApi#on} at a definition function).
*
* ```javascript
* var Model = $restmod.model('/', {
* '~afterInit': function() { alert('hello!'); }
* })
*
* // the after-init hook is called after every record initialization.
* Model.$new(); // alerts 'hello!';
* ```
*
* ## Definition function
*
* The definition function gives complete access to the model builder api, every model builder function described
* in this page can be called from the definition function by referencing *this*.
*
* ```javascript
* $restmod.model('', function() {
* this.attrDefault('propWithDefault', 20)
* .attrAsCollection('hasManyRelation', 'ModelName')
* .on('after-create', function() {
* // do something after create.
* });
* });
* ```
*
*/
function BuilderDSL(_targetModel) {
this.$$m = _targetModel;
this.$$mappings = {
init: ['attrDefault'],
mask: ['attrMask'],
ignore: ['attrMask'],
decode: ['attrDecoder', 'param', 'chain'],
encode: ['attrEncoder', 'param', 'chain'],
serialize: ['attrSerializer'],
// relations
hasMany: ['attrAsCollection', 'path', 'source', 'inverseOf'],
hasOne: ['attrAsResource', 'path', 'source', 'inverseOf'],
belongsTo: ['attrAsReference', 'inline', 'key', 'source', 'prefetch']
};
}
BuilderDSL.prototype = {
setHttpOptions: function(_options) {
// TODO.
},
/**
* @memberof BuilderApi#
*
* @description Sets an url prefix to be added to every url generated by the model.
*
* This applies even to objects generated by the `$single` method.
*
* This method is intended to be used in a base model mixin so everymodel that extends from it
* gets the same url prefix.
*
* Usage:
*
* ```javascript
* var BaseModel = $restmod.mixin(function() {
* this.setUrlPrefix('/api');
* })
*
* var bike = $restmod.model('/bikes', BaseModel).$build({ id: 1 });
* console.log(bike.$url()) // outputs '/api/bikes/1'
* ```
*
* @param {string} _prefix url portion
* @return {BuilderApi} self
*/
setUrlPrefix: function(_prefix) {
this.$$m.$$setUrlPrefix(_prefix);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Changes the model's primary key.
*
* Primary keys are passed to scope's url methods to generate urls. The default primary key is 'id'.
*
* **ATTENTION** Primary keys are extracted from raw data, so _key must use raw api naming.
*
* @param {string|function} _key New primary key.
* @return {BuilderApi} self
*/
setPrimaryKey: function(_key) {
this.$$m.$$setPrimaryKey(_key);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Changes the way restmod renames attributes every time a server resource is decoded.
*
* This is intended to be used as a way of keeping property naming style consistent accross
* languajes. By default, property naming in js should use camelcase and property naming
* in JSON api should use snake case with underscores.
*
* If `false` is given, then renaming is disabled
*
* @param {function|false} _value decoding function
* @return {BuilderApi} self
*/
setNameDecoder: function(_decoder) {
this.$$m.$$setNameDecoder(_decoder);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Changes the way restmod renames attributes every time a local resource is encoded to be sent.
*
* This is intended to be used as a way of keeping property naming style consistent accross
* languajes. By default, property naming in js should use camelcase and property naming
* in JSON api should use snake case with underscores.
*
* If `false` is given, then renaming is disabled
*
* @param {function|false} _value encoding function
* @return {BuilderApi} self
*/
setNameEncoder: function(_encoder) {
this.$$m.$$setNameEncoder(_encoder);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Disables renaming alltogether
*
* @return {BuilderApi} self
*/
disableRenaming: function() {
return this
.setNameDecoder(false)
.setNameEncoder(false);
},
/**
* @memberof BuilderApi#
*
* @description
*
* Sets the object "packer", the packer is responsable of providing the object wrapping strategy
* so it matches the API.
*
* The method accepts a packer name, an instance or a packer contructor, if the first (preferred)
* option is used, then a <Name>Packer factory must be available that return an object or a constructor.
*
* In case of using a constructor function, the constructor will be called passing the model type
* as first parameter:
*
* ```javascript
* // like this:
* var packer = new MyPacker(theModelType);
* ```
*
* ### Packer structure.
*
* Custom packers must implement the following methods:
*
* * **unpack(_rawData, _record):** unwraps data belonging to a single record, must return the unpacked
* data to be passed to `$decode`.
* * **unpackMany(_rawData, _collection):** unwraps the data belonging to a collection of records,
* must return the unpacked data array, each array element will be passed to $decode on each new element.
* * **pack(_rawData, _record):** wraps the encoded data from a record before is sent to the server,
* must return the packed data object to be sent.
*
* Currently the following builtin strategies are provided:
* TODO: provide builtin strategies!
*
* @param {string|object} _mode The packer instance, constructor or name
* @return {BuilderApi} self
*/
setPacker: function(_packer) {
this.$$m.$$setPacker(_packer);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Extends the builder DSL
*
* Adds a function to de builder and alternatively maps the function to an
* attribute definition keyword that can be later used when calling
* `define` or `attribute`.
*
* Mapping works as following:
*
* // Given the following call
* builder.extend('testAttr', function(_attr, _test, _param1, param2) {
* // wharever..
* }, ['test', 'testP1', 'testP2']);
*
* // A call to
* builder.attribute('chapter', { test: 'hello', testP1: 'world' });
*
* // Its equivalent to
* builder.testAttr('chapter', 'hello', 'world');
*
* The method can also be passed an object with various methods to be added.
*
* @param {string|object} _name function name or object to merge
* @param {function} _fun function
* @param {array} _mapping function mapping definition
* @return {BuilderApi} self
*/
extend: function(_name, _fun, _mapping) {
if(typeof _name === 'string') {
this[_name] = Utils.override(this[name], _fun);
if(_mapping) {
this.$$mappings[_mapping[0]] = _mapping;
_mapping[0] = _name;
}
} else Utils.extendOverriden(this, _name);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Parses a description object, calls the proper builder method depending
* on each property description type.
*
* @param {object} _description The description object
* @return {BuilderApi} self
*/
describe: function(_description) {
forEach(_description, function(_desc, _attr) {
switch(_attr.charAt(0)) {
case '@':
this.classDefine(_attr.substring(1), _desc);
break;
case '~':
_attr = $inflector.parameterize(_attr.substring(1));
this.on(_attr, _desc);
break;
default:
if(isObject(_desc)) this.attribute(_attr, _desc);
else if(isFunction(_desc)) this.define(_attr, _desc);
else this.attrDefault(_attr, _desc);
}
}, this);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Sets an attribute properties.
*
* This method uses the attribute modifiers mapping to call proper
* modifiers on the argument.
*
* For example, using the following description on the createdAt attribute
*
* { decode: 'date', param; 'YY-mm-dd' }
*
* Is the same as calling
*
* builder.attrDecoder('createdAt', 'date', 'YY-mm-dd')
*
* @param {string} _name Attribute name
* @param {object} _description Description object
* @return {BuilderApi} self
*/
attribute: function(_name, _description) {
var key, map, args, i;
for(key in _description) {
if(_description.hasOwnProperty(key)) {
map = this.$$mappings[key];
if(map) {
args = [_name, _description[key]];
for(i = 1; i < map.length; i++) {
args.push(_description[map[i]]);
}
args.push(_description);
this[map[0]].apply(this, args);
}
}
}
return this;
},
/**
* @memberof BuilderApi#
*
* @description Sets the default value for an attribute.
*
* Defaults values are set only on object construction phase.
*
* if `_init` is a function, then its evaluated every time the
* default value is required.
*
* @param {string} _attr Attribute name
* @param {mixed} _init Defaulf value / iniline function
* @return {BuilderApi} self
*/
attrDefault: function(_attr, _init) {
this.$$m.$$setDefault(_attr, _init);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Sets an attribute mask.
*
* An attribute mask prevents the attribute to be loaded from or sent to the server on certain operations.
*
* The attribute mask is a string composed by:
* * C: To prevent attribute from being sent on create
* * R: To prevent attribute from being loaded from server
* * U: To prevent attribute from being sent on update
*
* For example, the following will prevent an attribute to be send on create or update:
*
* ```javascript
* builder.attrMask('readOnly', 'CU');
* ```
*
* If a true boolean value is passed as mask, then 'CRU' will be used
* If a false boolean valus is passed as mask, then mask will be removed
*
* @param {string} _attr Attribute name
* @param {boolean|string} _mask Attribute mask
* @return {BuilderApi} self
*/
attrMask: function(_attr, _mask) {
this.$$m.$$setMask(_attr, _mask);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Assigns a serializer to a given attribute.
*
* A _serializer is:
* * an object that defines both a `decode` and a `encode` method
* * a function that when called returns an object that matches the above description.
* * a string that represents an injectable that matches any of the above descriptions.
*
* @param {string} _name Attribute name
* @param {string|object|function} _serializer The serializer
* @return {BuilderApi} self
*/
attrSerializer: function(_name, _serializer, _opt) {
if(typeof _serializer === 'string') {
_serializer = $injector.get($inflector.camelize(_serializer, true) + 'Serializer');
}
// TODO: if(!_serializer) throw $setupError
if(isFunction(_serializer)) _serializer = _serializer(_opt);
if(_serializer.decode) this.$$m.$$setDecoder(_name, bind(_serializer, _serializer.decode));
if(_serializer.encode) this.$$m.$$setEncoder(_name, bind(_serializer, _serializer.encode));
return this;
},
/**
* @memberof BuilderApi#
*
* @description Assigns a decoding function/filter to a given attribute.
*
* @param {string} _name Attribute name
* @param {string|function} _filter filter or function to register
* @param {mixed} _filterParam Misc filter parameter
* @param {boolean} _chain If true, filter is chained to the current attribute filter.
* @return {BuilderApi} self
*/
attrDecoder: function(_name, _filter, _filterParam, _chain) {
this.$$m.$$setDecoder(_name, _filter, _filterParam, _chain);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Assigns a encoding function/filter to a given attribute.
*
* @param {string} _name Attribute name
* @param {string|function} _filter filter or function to register
* @param {mixed} _filterParam Misc filter parameter
* @param {boolean} _chain If true, filter is chained to the current attribute filter.
* @return {BuilderApi} self
*/
attrEncoder: function(_name, _filter, _filterParam, _chain) {
this.$$m.$$setEncoder(_name, _filter, _filterParam, _chain);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Registers a model **resources** relation
*
* @param {string} _name Attribute name
* @param {string|object} _model Other model, supports a model name or a direct reference.
* @param {string} _url Partial url
* @param {string} _source Inline resource alias (optional)
* @param {string} _inverseOf Inverse property name (optional)
* @return {BuilderApi} self
*/
attrAsCollection: function(_attr, _model, _url, _source, _inverseOf) {
this.$$m.$$setDefault(_attr, function() {
if(typeof _model === 'string') {
_model = $injector.get(_model);
if(_inverseOf) {
_model.$$setMask(_inverseOf, Utils.WRITE_MASK);
}
}
var self = this,
scope = this.$buildScope(_model, _url || $inflector.parameterize(_attr)),
col = _model.$collection(null, scope);
// TODO: there should be a way to modify scope behavior just for this relation,
// since relation item scope IS the collection, then the collection should
// be extended to provide a modified scope. For this an additional _extensions
// parameters could be added to collection, then these 'extensions' are inherited
// by child collections, the other alternative is to enable full property inheritance ...
// set inverse property if required.
if(_inverseOf) {
col.$on('after-add', function(_obj) {
_obj[_inverseOf] = self;
});
}
return col;
// simple support for inline data, TODO: maybe deprecate this.
});
this.$$m.$$setDecoder(_source || _url || _attr, function(_raw) {
this[_attr].$reset().$feed(_raw);
});
this.$$m.$$setMask(_attr, Utils.WRITE_MASK);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Registers a model **resource** relation
*
* @param {string} _name Attribute name
* @param {string|object} _model Other model, supports a model name or a direct reference.
* @param {string} _url Partial url (optional)
* @param {string} _source Inline resource alias (optional)
* @param {string} _inverseOf Inverse property name (optional)
* @return {BuilderApi} self
*/
attrAsResource: function(_attr, _model, _url, _source, _inverseOf) {
this.$$m.$$setDefault(_attr, function() {
if(typeof _model === 'string') {
_model = $injector.get(_model);
if(_inverseOf) {
_model.$$setMask(_inverseOf, Utils.WRITE_MASK);
}
}
var scope = this.$buildScope(_model, _url || $inflector.parameterize(_attr)),
inst = _model.$new(null, scope);
// TODO: provide a way to modify scope behavior just for this relation
if(_inverseOf) {
inst[_inverseOf] = this;
}
return inst;
});
// simple support for inline data, TODO: maybe deprecate this.
this.$$m.$$setDecoder(_source || _url || _attr, function(_raw) {
this[_attr].$decode(_raw);
});
this.$$m.$$setMask(_attr, Utils.WRITE_MASK);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Registers a model **reference** relation.
*
* A reference relation
*
* @param {string} _name Attribute name
* @param {string|object} _model Other model, supports a model name or a direct reference.
* @param {bool} _inline If true, model data is expected to be inlined in parent response.
* @param {string} _key reference id property name (optional, defaults to _attr + 'Id')
* @param {bool} _prefetch if set to true, $fetch will be automatically called on relation object load.
* @return {BuilderApi} self
*/
attrAsReference: function(_attr, _model, _inline, _key, _source, _prefetch) {
var watch = _inline ? (_source || _attr) : (_key || (_attr + 'Id'));
this.$$m.$$setDefault(_attr, null);
this.$$m.$$setMask(_attr, Utils.WRITE_MASK);
this.$$m.$$setDecoder(watch , function(_raw) {
// load model
if(typeof _model === 'string') {
_model = $injector.get(_model);
}
// only reload object if id changes
if(_inline)
{
if(!this[_attr] || this[_attr].$pk !== _model.$$inferKey(_raw)) {
this[_attr] = _model.$buildRaw(_raw);
} else {
this[_attr].$decode(_raw);
}
}
else
{
if(!this[_attr] || this[_attr].$pk !== _raw) {
this[_attr] = _model.$new(_raw); // use $new instead of $build
if(_prefetch) {
this[_attr].$fetch();
}
}
}
});
return this;
},
/**
* @memberof BuilderApi#
*
* @description Registers an instance method
*
* Usage:
* builder.define(function(_super) {
* return $fetch()
* });
*
* It is posible to override an existing method using define,
* if overriden, the old method can be called using `this.$super`
* inside de new method.
*
* @param {string} _name Method name
* @param {function} _fun Function to define
* @return {BuilderApi} self
*/
define: function(_name, _fun) {
if(typeof _name === 'string') {
this.$$m.prototype[_name] = Utils.override(this.$$m.prototype[_name], _fun);
} else {
Utils.extendOverriden(this.$$m.prototype, _name);
}
return this;
},
/**
* @memberof BuilderApi#
*
* @description Registers a class method
*
* It is posible to override an existing method using define,
* if overriden, the old method can be called using `this.$super`
* inside de new method.
*
* @param {string} _name Method name
* @param {function} _fun Function to define
* @return {BuilderApi} self
*/
classDefine: function(_name, _fun) {
this.$$m.$$addScopeMethod(_name, _fun);
return this;
},
/**
* @memberof BuilderApi#
*
* @description Adds an event hook
*
* Hooks are used to extend or modify the model behavior, and are not
* designed to be used as an event listening system.
*
* The given function is executed in the hook's context, different hooks
* make different parameters available to callbacks.
*
* @param {string} _hook The hook name, refer to restmod docs for builtin hooks.
* @param {function} _do function to be executed
* @return {BuilderApi} self
*/
on: function(_hook, _do) {
this.$$m.$on(_hook, _do);
return this;
},
/// Experimental modifiers
/**
* @memberof BuilderApi#
*
* @description Expression attributes are evaluated every time new data is fed to the model.
*
* @param {string} _name Attribute name
* @param {string} _expr Angular expression to evaluate
* @return {BuilderApi} self
*/
attrExpression: function(_name, _expr) {
var filter = $parse(_expr);
this.$$m.$on('after-feed', function() {
this[_name] = filter(this);
});
return this;
}
};
function Builder(_target) {
this.dsl = new BuilderDSL(_target);
}
Builder.prototype = {
// use the builder to process a mixin chain
loadMixinChain: function(_chain) {
for(var i = 0, l = _chain.length; i < l; i++) {
this.loadMixin(_chain[i]);
}
},
// use the builder to process a single mixin
loadMixin: function(_mix) {
if(_mix.$chain) {
this.loadMixinChain(_mix.$chain);
} else if(typeof _mix === 'string') {
this.loadMixin($injector.get(_mix));
} else if(isArray(_mix) || isFunction(_mix)) {
// TODO: maybe invoke should only be called for BASE_CHAIN functions
$injector.invoke(_mix, this.dsl, { $builder: this.dsl });
} else this.dsl.describe(_mix);
}
};
return Builder;
}]);
RMModule.factory('RMCollectionApi', ['RMUtils', function(Utils) {
var extend = angular.extend;
/**
* @class CollectionApi
*
* @extends ScopeApi
* @extends CommonApi
*
* @description
*
* A restmod collection is an extended array type bound REST resource route.
*
* Every time a new restmod model is created, an associated collection type is created too.
*
* TODO: talk about fetch/refresh behaviour, lifecycles, collection scopes, adding/removing
*
* For `$fetch` on a collection:
*
* * before-fetch-many
* * before-request
* * after-request[-error]
* * after-feed (only called if no errors)
* * after-fetch-many[-error]
*
* @property {boolean} $isCollection Helper flag to separate collections from the main type
* @property {object} $scope The collection scope (hierarchical scope, not angular scope)
* @property {object} $params The collection query parameters
* @property {boolean} $resolved The collection resolve status
*
*/
return {
/**
* @memberof CollectionApi#
*
* @description Gets this collection url without query string.
*
* @return {string} The collection url.
*/
$url: function() {
return this.$scope.$url();
},
/**
* @memberof CollectionApi#
*
* @description Part of the scope interface, provides urls for collection's items.
*
* @param {RecordApi} _pk Item key to provide the url to.
* @return {string|null} The url or nill if item does not meet the url requirements.
*/