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
3987 lines (3586 loc) · 122 KB
/
Copy pathangular-restmod.js
File metadata and controls
3987 lines (3586 loc) · 122 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 v1.1.11 - 2015-10-26
* @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('restmod', ['ng', 'platanus.inflector']);
/**
* @class restmodProvider
*
* @description
*
* The restmodProvider exposes restmod configuration methods
*/
RMModule.provider('restmod', [function() {
var BASE_CHAIN = ['RMBuilderExt', 'RMBuilderRelations', 'RMBuilderComputed'];
function wrapInInvoke(_mixin) {
return function(_injector) {
_injector.invoke(_mixin, this, { $builder: this });
};
}
return {
/**
* @memberof restmodProvider#
*
* @description
*
* Adds base mixins for every generated model.
*
* **ATTENTION** Model names should NOT be added to this chain.
*
* All mixins added to the chain are prepended to every generated model.
*
* Usage:
*
* ```javascript
* $provider.rebase('ChangeModel', 'LazyRelations', 'ThrottledModel')
* ```
*/
rebase: function(/* _mix_names */) {
var mixin, i, l = arguments.length;
for(i = 0; i < l; i++) {
mixin = arguments[i];
if(angular.isArray(mixin) || angular.isFunction(mixin)) {
mixin = wrapInInvoke(mixin);
}
BASE_CHAIN.push(mixin);
}
return this;
},
/**
* @class restmod
*
* @description
*
* The restmod service provides factory methods for the different restmod consumables.
*/
$get: ['RMModelFactory', '$log', function(buildModel, $log) {
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 *nested* 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 */) {
var model = buildModel(_baseUrl, BASE_CHAIN);
if(arguments.length > 1) {
model.mix(arraySlice.call(arguments, 1));
$log.warn('Passing mixins and definitions in the model method will be deprecated in restmod 1.2, use restmod.model().mix() instead.');
}
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#rebase} 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('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 (called for every record if no errors)
* * after-feed-many (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
*
*/
return {
$isCollection: true,
/**
* @memberof CollectionApi#
*
* @description Called by collection constructor on initialization.
*
* Note: Is better to add a hook on after-init than overriding this method.
*/
$initialize: function() {
// after initialization hook
this.$dispatch('after-collection-init');
},
/**
* @memberof CollectionApi#
*
* @description Feeds raw collection data into the collection.
*
* This method is for use in collections only.
*
* @param {array} _raw Data to add
* @param {string} _mask 'CRU' mask
* @return {CollectionApi} self
*/
$decode: function(_raw, _mask) {
Utils.assert(_raw && angular.isArray(_raw), 'Collection $decode expected array');
for(var i = 0, l = _raw.length; i < l; i++) {
this.$buildRaw(_raw[i], _mask).$reveal(); // build and disclose every item.
}
this.$dispatch('after-feed-many', [_raw]);
return this;
},
/**
* @memberof CollectionApi#
*
* @description Encodes array data into a its serialized version.
*
* @param {string} _mask 'CRU' mask
* @return {CollectionApi} self
*/
$encode: function(_mask) {
var raw = [];
for(var i = 0, l = this.length; i < l; i++) {
raw.push(this[i].$encode(_mask));
}
this.$dispatch('before-render-many', [raw]);
return raw;
},
/**
* @memberof CollectionApi#
*
* @description Resets the collection's contents
*
* @return {CollectionApi} self
*/
$clear: function() {
return this.$always(function() {
this.length = 0; // reset the collection contents
});
},
/**
* @memberof CollectionApi#
*
* @description Begin a server request to populate collection. This method does not
* clear the collection contents by default, use `$refresh` to reset and fetch.
*
* This method is for use in collections only.
*
* @param {object|function} _params Additional request parameters, not stored in collection,
* if a function is given, then it will be called with the request object to allow requet customization.
* @return {CollectionApi} self
*/
$fetch: function(_params) {
return this.$action(function() {
var request = { method: 'GET', url: this.$url('fetchMany'), params: this.$params };
if(_params) {
request.params = request.params ? extend(request.params, _params) : _params;
}
// TODO: check that collection is bound.
this
.$dispatch('before-fetch-many', [request])
.$send(request, function(_response) {
this
.$unwrap(_response.data)
.$dispatch('after-fetch-many', [_response]);
}, function(_response) {
this.$dispatch('after-fetch-many-error', [_response]);
});
});
},
/**
* @memberof CollectionApi#
*
* @description Adds an item to the back of the collection. This method does not attempt to send changes
* to the server. To create a new item and add it use $create or $build.
*
* Triggers after-add callbacks.
*
* @param {RecordApi} _obj Item to be added
* @return {CollectionApi} self
*/
$add: function(_obj, _idx) {
Utils.assert(_obj.$type && _obj.$type === this.$type, 'Collection $add expects record of the same $type');
return this.$action(function() {
if(_obj.$position === undefined) {
if(_idx !== undefined) {
this.splice(_idx, 0, _obj);
} else {
this.push(_obj);
}
_obj.$position = true; // use true for now, keeping position updated can be expensive
this.$dispatch('after-add', [_obj]);
}
});
},
/**
* @memberof CollectionApi#
*
* @description Removes an item from the collection.
*
* This method does not send a DELETE request to the server, it just removes the
* item locally. To remove an item AND send a DELETE use the item's $destroy method.
*
* Triggers after-remove callbacks.
*
* @param {RecordApi} _obj Item to be removed
* @return {CollectionApi} self
*/
$remove: function(_obj) {
return this.$action(function() {
var idx = this.$indexOf(_obj);
if(idx !== -1) {
this.splice(idx, 1);
_obj.$position = undefined;
this.$dispatch('after-remove', [_obj]);
}
});
},
/**
* @memberof CollectionApi#
*
* @description Finds the location of an object in the array.
*
* If a function is provided then the index of the first item for which the function returns true.
*
* @param {RecordApi|function} _obj Object to find
* @param {integer} _fromIdx Index from which to start searching, defaults to 0
* @return {number} Object index or -1 if not found
*/
$indexOf: function(_obj, _fromIdx) {
var accept = typeof _obj !== 'function' ?
function(e) { return e === _obj; } : _obj;
return Utils.indexWhere(this, accept, _fromIdx);
}
};
}]);
RMModule.factory('RMCommonApi', ['$http', 'RMFastQ', '$log', 'RMUtils', function($http, $q, $log, Utils) {
var EMPTY_ARRAY = [];
function wrapPromise(_ctx, _fun) {
var dsp = _ctx.$dispatcher();
return function(_last) {
// save and reset promise
var oldPromise = _ctx.$promise;
_ctx.$promise = undefined;
try {
_ctx.$last = _last;
var result = dsp ? _ctx.$decorate(dsp, _fun, [_ctx]) : _fun.call(_ctx, _ctx);
return result === undefined ? _ctx.$promise : result;
} finally {
_ctx.$promise = oldPromise; // restore old promise
}
};
}
/**
* @class CommonApi
*
* @description
*
* Provides a common framework for restmod resources.
*
* This API is included in {@link RecordApi} and {@link CollectionApi}.
* making its methods available in every structure generated by restmod.
*
* TODO: Describe hook mechanism, promise mechanism and send lifecycle.
*
* @property {promise} $promise The last operation promise (undefined if no promise has been created yet)
* @property {array} $pending Pending requests associated to this resource (undefined if no request has been initiated)
* @property {object} $$cb Scope call backs (undefined if no callbacks have been defined, private api)
* @property {function} $$dsp The current event dispatcher (private api)
*/
var CommonApi = {
/**
* @memberof CommonApi#
*
* @description Gets this resource url.
*
* @param {string} _for Intended usage for the url (optional)
* @return {string} The resource url.
*/
$url: function(_for) {
if(_for) {
_for = '$' + _for + 'UrlFor';
if(this.$scope[_for]) return this.$scope[_for](this);
} else if(this.$scope.$canonicalUrlFor) {
return this.$scope.$canonicalUrlFor(this);
}
return this.$scope.$urlFor(this);
},
// Hooks API
/**
* @memberof CommonApi#
*
* @description Executes a given hook callbacks using the current dispatcher context.
*
* This method can be used to provide custom object lifecycle hooks.
*
* Usage:
*
* ```javascript
* var mixin = restmod.mixin({
* triggerDummy: function(_param) {
* this.$dispatch('dummy-hook', _param);
* }
* });
*
* // Then hook can be used at model definition to provide type-level customization:
* var Bike $resmod.model('/api/bikes', mixin, {
* '~dummy-hook': function() {
* alert('This is called for every bike');
* }
* };
*
* // or at instance level:
* var myBike = Bike.$build();
* myBike.$on('dummy-hook', function() {
* alert('This is called for myBike only');
* });
*
* // or event at decorated context level
* myBike.$decorate({
* 'dummy-hook': function() {
* alert('This is called for myBike only inside the decorated context');
* }
* }, fuction() {
* // decorated context
* });
* ```
*
* @param {string} _hook Hook name
* @param {array} _args Hook arguments
* @param {object} _ctx Hook execution context override
*
* @return {CommonApi} self
*/
$dispatch: function(_hook, _args, _ctx) {
var cbs, i, cb, dsp = this.$$dsp;
if(!_ctx) _ctx = this;
// context callbacks
if(dsp) {
this.$$dsp = undefined; // disable dsp for hooks
dsp(_hook, _args, _ctx);
}
// instance callbacks
if(this.$$cb && (cbs = this.$$cb[_hook])) {
for(i = 0; !!(cb = cbs[i]); i++) {
cb.apply(_ctx, _args || EMPTY_ARRAY);
}
}
// bubble up the object scope, bubble to type only if there isnt a viable parent scope.
if(this.$scope && this.$scope.$dispatch) {
this.$scope.$dispatch(_hook, _args, _ctx);
} else if(this.$type) {
this.$type.$dispatch(_hook, _args, _ctx);
}
this.$$dsp = dsp; // reenable dsp.
return this;
},
/**
* @memberof CommonApi#
*
* @description Registers an instance hook.
*
* An instance hook is called only for events generated by the calling object.
*
* ```javascript
* var bike = Model.$build(), bike2 = Model.$build();
* bike.$on('before-save', function() { alert('saved!'); });
*
* bike.$save(); // 'saved!' alert is shown after bike is saved
* bike2.$save(); // no alert is shown after bike2 is saved
* ```
*
* @param {string} _hook Hook name
* @param {function} _fun Callback
* @return {CommonApi} self
*/
$on: function(_hook, _fun) {
var hooks = (this.$$cb || (this.$$cb = {}))[_hook] || (this.$$cb[_hook] = []);
hooks.push(_fun);
return this;
},
/**
* @memberof CommonApi#
*
* @description Unregisters an instance hook registered with `$on`
*
* @param {string} _hook Hook name
* @param {function} _fun Original callback
* @return {CommonApi} self
*/
$off: function(_hook, _fun) {
if(this.$$cb && this.$$cb[_hook]) {
var idx = Utils.indexWhere(this.$$cb[_hook], function(e) { return e === _fun; });
if(idx !== -1) this.$$cb[_hook].splice(idx, 1);
}
return this;
},
/**
* @memberof CommonApi#
*
* @description Registers hooks to be used only inside the given function (decorated context).
*
* ```javascript
* // special fetch method that sends a special token header.
* restmod.mixin({
* $fetchWithToken: function(_token) {
* return this.$decorate({
* 'before-fetch': function(_req) {
* _req.headers = _req.headers || {};
* _req.headers['Token'] = _token;
* }
* ), function() {
* return this.$fetch();
* })
* }
* });
* ```
*
* @param {object|function} _hooks Hook mapping object or hook execution method.
* @param {function} _fun Function to be executed in with decorated context, this function is executed in the callee object context.
* @return {CommonApi} self
*/
$decorate: function(_hooks, _fun, _args) {
var oldDispatcher = this.$$dsp;
// set new dispatcher
this.$$dsp = (typeof _hooks === 'function' || !_hooks) ? _hooks : function(_hook, _args, _ctx) {
if(oldDispatcher) oldDispatcher.apply(null, arguments);
var extraCb = _hooks[_hook];
if(extraCb) extraCb.apply(_ctx, _args || EMPTY_ARRAY);
};
try {
return _fun.apply(this, _args);
} finally {
// reset dispatcher with old value
this.$$dsp = oldDispatcher;
}
},
/**
* @memberof CommonApi#
*
* @description Retrieves the current object's event dispatcher function.
*
* This method can be used in conjuction with `$decorate` to provide a consistent hook context
* during async operations. This is important when building extensions that want to support the
* contextual hook system in asynchronic operations.
*
* For more information aboout contextual hooks, see the {@link CommonApi#decorate} documentation.
*
* Usage:
*
* ```javascript
* restmod.mixin({
* $saveAndTrack: function() {
* var dsp = this.$dispatcher(), // capture the current dispatcher function.
* self = this;
* this.$save().$then(function() {
* this.$send({ path: '/traces', data: 'ble' }, function() {
* this.$decorate(dsp, function() {
* // the event is dispatched using the dispatcher function available when $saveAndTrack was called.
* this.$dispatch('trace-stored');
* });
* });
* });
* }
* })
* ```
*
* @return {function} Dispatcher evaluator
*/
$dispatcher: function() {
return this.$$dsp;
},
// Promise API
/**
* @memberof CommonApi#
*
* @description Returns this object last promise.
*
* If promise does not exist, then a new one is generated that resolves to the object itsef. The
* new promise is not set as the current object promise, for that use `$then`.
*
* Usage:
*
* ```javascript
* col.$fetch().$asPromise();
* ```
*
* @return {promise} $q promise
*/
$asPromise: function() {
var _this = this;
return this.$promise ? this.$promise.then(
function() { return _this; },
function() { return $q.reject(_this); }
) : $q.when(this);
},
/**
* @memberof CommonApi#
*
* @description Promise chaining method, keeps the model instance as the chain context.
*
* Calls `$q.then` on the model's last promise.
*
* Usage:
*
* ```javascript
* col.$fetch().$then(function() { });
* ```
*
* @param {function} _success success callback
* @param {function} _error error callback
* @return {CommonApi} self
*/
$then: function(_success, _error) {
if(!this.$promise) {
this.$promise = $q.when(wrapPromise(this, _success)(this));
} else {
this.$promise = this.$promise.then(
_success ? wrapPromise(this, _success) : _success,
_error ? wrapPromise(this, _error) : _error
);
}
return this;
},
/**
* @memberof CommonApi#
*
* @description Promise chaining method, similar to then but executes same callback in success or error.
*
* Usage:
*
* ```javascript
* col.$fetch().$always(function() { });
* ```
*
* @param {function} _fun success/error callback
* @return {CommonApi} self
*/
$always: function(_fun) {
return this.$then(_fun, _fun);
},
/**
* @memberof CommonApi#
*
* @description Promise chaining, keeps the model instance as the chain context.
*
* Calls ´$q.finally´ on the collection's last promise, updates last promise with finally result.
*
* Usage:
*
* ```javascript
* col.$fetch().$finally(function() { });
* ```
*
* @param {function} _cb callback
* @return {CommonApi} self
*/
$finally: function(_cb) {
this.$promise = this.$promise['finally'](wrapPromise(this, _cb));
return this;
},
// Communication API
/**
* @memberof CommonApi#
*
* @description Low level communication method, wraps the $http api.
*
* * You can access last request promise using the `$asPromise` method.
* * Pending requests will be available at the $pending property (array).
* * Current request execution status can be queried using the $status property (current request, not last).
* * The $status property refers to the current request inside $send `_success` and `_error` callbacks.
*
* @param {object} _options $http options
* @param {function} _success sucess callback (sync)
* @param {function} _error error callback (sync)
* @return {CommonApi} self
*/
$send: function(_options, _success, _error) {
// make sure a style base was selected for the model
if(!this.$type.getProperty('style')) {
$log.warn('No API style base was selected, see the Api Integration FAQ for more information on this warning');
}
var action = this.$$action;
return this.$always(function() {
this.$response = null;
this.$status = 'pending';
this.$dispatch('before-request', [_options]);
return $http(_options).then(wrapPromise(this, function() {
if(action && action.canceled) {
this.$status = 'canceled';
this.$dispatch('after-request-cancel', []);
return $q.reject(this);
} else {
this.$status = 'ok';
this.$response = this.$last;
this.$dispatch('after-request', [this.$response]);
if(_success) _success.call(this, this.$response);
}
}), wrapPromise(this, function() {
if(action && action.canceled) {
this.$status = 'canceled';
this.$dispatch('after-request-cancel', []);
} else {
this.$status = 'error';
this.$response = this.$last;
// IDEA: Consider flushing pending request in case of an error. Also continue ignoring requests
// until the error flag is reset by user.
this.$dispatch('after-request-error', [this.$response]);
if(_error) _error.call(this, this.$response);
}
return $q.reject(this); // TODO: this will step over any promise generated in _error!!
}));
});
},
// Actions API
/**
* @memberof CommonApi#
*
* @description Registers a new action to be executed in the promise queue.
*
* Registered pending actions can be canceled using `$cancel`
*
* `$cancel` will also cancel any ongoing call to `$send` (will not abort it yet though...)
*
* @return {CommonApi} self
*/
$action: function(_fun) {
var status = {
canceled: false
}, pending = this.$pending || (this.$pending = []);
pending.push(status);
return this.$always(function() {
var oldAction = this.$$action;
try {
if(!status.canceled) {
this.$$action = status;
return _fun.call(this);
} else {
return $q.reject(this);
}
} finally {
// restore object state and pending actions
this.$$action = oldAction;
}
}).$finally(function() {
// after action and related async code finishes, remove status from pending list
pending.splice(pending.indexOf(status), 1);
});
},
/**
* @memberof CommonApi#
*
* @description Cancels all pending actions registered with $action.
*
* @return {CommonApi} self
*/
$cancel: function() {
// cancel every pending request.
if(this.$pending) {
angular.forEach(this.$pending, function(_status) {
_status.canceled = true;
});
}
return this;
},
/**
* @memberof CommonApi#
*
* @description Returns true if object has queued actions
*
* @return {Boolean} Object request pending status.
*/
$hasPendingActions: function() {
var pendingCount = 0;
if(this.$pending) {
angular.forEach(this.$pending, function(_status) {
if(!_status.canceled) pendingCount++;
});
}
return pendingCount > 0;
}
};
return CommonApi;
}]);
RMModule.factory('RMExtendedApi', ['$q', 'RMPackerCache', function($q, packerCache) {
/**
* @class ExtendedApi
*
* @description
*
* Provides a common framework **on top** of the {@link RecordApi} and {@link CollectionApi}.
*
* @property {boolean} $resolved The collection resolve status, is undefined on intialization
*/
return {
// override decode to detect resolution of resource
$decode: function(_raw, _mask) {
if(this.$resolved === false && this.$clear) this.$clear(); // clear if not resolved.
this.$super(_raw, _mask);
this.$resolved = true;
return this;
},
/// Misc common methods
/**
* @memberof ExtendedApi#
*
* @description
*
* Unpacks and decode raw data from a server generated structure.
*
* ATTENTION: do not override this method to change the object wrapping strategy,
* instead, override the static {@link Model.$unpack} method.
*
* @param {mixed} _raw Raw server data
* @param {string} _mask 'CRU' mask
* @return {ExtendedApi} this
*/
$unwrap: function(_raw, _mask) {
try {
packerCache.prepare();
_raw = this.$type.unpack(this, _raw);
return this.$decode(_raw, _mask);
} finally {
packerCache.clear();
}
},
/**
* @memberof ExtendedApi#
*
* @description
*
* Encode and packs object into a server compatible structure that can be used for PUT/POST operations.
*
* ATTENTION: do not override this method to change the object wrapping strategy,
* instead, override the static {@link Model.$pack} method.
*
* @param {string} _mask 'CRU' mask
* @return {string} raw data
*/
$wrap: function(_mask) {
var raw = this.$encode(_mask);
raw = this.$type.pack(this, raw);
return raw;
},
/**
* @memberof ExtendedApi#
*
* @description Resets the resource's $resolved status.
*
* After being reset, calls to `$resolve` will execute a new $fetch.
*
* Also, if reset, resource will be cleared on new data.
*
* @return {ExtendedApi} self
*/
$reset: function() {
// cancel outside promise chain
// TODO: find a way of only ignoring requests that will lead to resolution, maybe using action metadata
return this.$cancel().$action(function() {
this.$resolved = false;
});
},
/**
* @memberof ExtendedApi#
*
* @description Resolves the resource's contents.
*
* If already resolved then this method will return a resolved promise, if not then
* it will initiate a `$fetch` operation and return the operation promise.
*
* This method will trigger a `before-resolve` event before checking the resolve status.
*
* @param {object} _params `$fetch` params
* @return {promise} Promise that resolves to the resource.
*/
$resolve: function(_params) {
return this.$action(function() { // chain resolution in request promise chain
this.$dispatch('before-resolve', []);
if(!this.$resolved) this.$fetch(_params);
});
},