forked from deepjs/deepjs
/
deep.js
2960 lines (2855 loc) · 106 KB
/
deep.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
/**
* @module deep
* @author Gilles Coomans <gilles.coomans@gmail.com>
*/
if (typeof define !== 'function')
var define = require('amdefine')(module);
define(["require", "./utils", "./deep-rql", "./deep-schema", "./deep-query", "./deep-compose", "./deep-collider", "./deep-errors", "./deep-stores", "./deep-ocm"], function (require) {
deep = function deepStart(obj, schema, options) {
//console.log("start chain : ", obj)
//if(obj && obj._deep_chain_ && obj.oldQueue)
// return obj;
var h = new deep.Chain(options);
try {
if (typeof obj === 'string')
obj = deep.get(obj);
if (typeof schema === 'string')
schema = deep.get(schema);
var doStart = function doStartChain(obj, schema) {
//if(obj._deep_entry)
//console.log("do start : ", obj)
var r = obj;
if (obj && obj._isDQ_NODE_)
{
r = obj.value;
h._nodes = [obj];
}
else if (obj && obj._deep_store_)
{
h._nodes = [deep.Querier.createRootNode({}, options)];
h.store(obj);
deep.Store.extendsChain(h);
}
else if (obj && obj._deep_entry)
{
r = obj._deep_entry.value;
h._nodes = [obj._deep_entry];
}
else
h._nodes = [deep.Querier.createRootNode(obj, schema, options)];
h._root = h._nodes[0];
h._start(r, null);
};
var alls = null;
if (obj && (obj.then || obj.promise))
alls = [obj, schema];
if(alls){
//console.log("chain start with deferred or promise : ", obj)
deep.all(alls)
.done(function (res) {
//console.log("deep start chain res : ",res);
doStart(res[0], res[1]);
})
.fail(function (error) {
h._nodes = null;
h._start(null, error);
});
} else
doStart(obj, schema);
} catch (error) {
console.log("internal chain start error : ", error);
h._nodes = [deep.Querier.createRootNode({}, schema, options)];
h._start(null, error);
}
return h;
};
var errors = require("deep/deep-errors")(deep);
/**
* final namespace for deep/deep-compose
* @static
* @property compose
* @type {Object}
*/
deep.compose = require("./deep-compose")(deep);
/**
* final namespace for deep/deep-collider
* @static
* @property collider
* @type {Object}
*/
deep.collider = require("./deep-collider")(deep);
/**
* rethrow any throw during chain execution.
* @property rethrow
* @static
* @type {Boolean}
*/
deep.rethrow = false;
deep.metaSchema = {};
/**
* final namespace for deep/utils
* @static
* @property utils
* @type {Object}
*/
var utils = deep.utils = require("./utils")(deep);
/**
* perform a (synched) deep-rql filter on array
* @example
*
* deep.rql(["a","b","c"], "=a"); // return ["a"]
*
* @static
* @method rql
* @param {Array} array the array to filter
* @param {String} rqlFilter the rql filter to apply
* @return {Array} the result aray
*/
deep.rql = require("./deep-rql")(utils).query;
/**
* final namespace for deep/deep-query
* @static
* @property Querier
* @type {DeepQuery}
*/
var Querier = deep.Querier = require("./deep-query")(deep);
/**
* the deep schema validator
* @static
* @property Validator
*/
deep.Validator = require("./deep-schema")(deep);
/**
* perform a deep-schema validation
* @static
* @method validate
* @param object the object to validate
* @param schema the schema
* @return {deep.validate.Report} the validation report
*/
deep.validate = deep.Validator.validate;
/**
* perform a deep-schema partial validation (only on certain field)
* @static
* @method partialValidation
* @param object the object to validate
* @param fields the array of properties paths to validate
* @param schema the schema
* @return {deep.validate.Report} the validation report
*/
deep.partialValidation = deep.Validator.partialValidation;
/**
* are you on nodejs or not
* @static
* @property isNode
* @type {Boolean}
*/
deep.isNode = (typeof process !== 'undefined' && process.versions && process.versions.node);
/**
* perform a (synched) deep-query query
* @example
*
* deep.query({ hello:"world", test:1 }, "/*?=world"); // will return ["world"]
*
* @method query
* @param {Object} object any object to query
* @param {String} query the query
* @static
* @return {Array} the result aray
*/
deep.query = Querier.query;
/**
* shortcut for utils.interpret
* @static
* @method interpret
* @param {String} string the string to interpret
* @param {Object} context the context injected for interpretation
* @return {String} the result
*/
deep.interpret = utils.interpret;
/**
* a magic context that follow promise context and switch automaticaly
* @static
* @property interpret
*/
deep.context = {};
/**
* where to place YOUR globals (deep does'nt have any globals)
* @static
* @property globals
*/
deep.globals = {};
/**
* where to place YOUR globals headers to set on each store call (deep does'nt have any globals)
* @static
* @property globals
*/
deep.globalHaders = {};
deep.destructiveLoad = false;
var addInChain = function addInChain(handle) {
var self = this;
if (self.deferred && (self.deferred.rejected || self.deferred.resolved))
throw deep.errors.Internal("you try to add handles in ended chain ! aborting and throw.");
self._queue.push(handle);
if (self._initialised && !self._running && !self._executing)
self._forceHandle();
return this;
}
var forceHandle = function forceChainHandle() {
if (!this._initialised)
return;
var self = this;
if (this.oldQueue) {
this._queue = this._queue.concat(this.oldQueue);
delete this.oldQueue;
}
if (self._queue.length > 0) {
self._executing = true; // synch flag
while (!self._running) // while not asynch
{
var previousContext = deep.context;
try {
if (previousContext !== self._context) {
if (previousContext && previousContext.suspend)
previousContext.suspend();
deep.context = self._context;
if (self._context && self._context.resume)
self._context.resume();
}
// get next handle : if no more handle : just break;
var next = self._queue.shift();
if (self._error)
while (next && next._isDone_)
next = self._queue.shift();
else
while (next && next._isFail_)
next = self._queue.shift();
if (!next)
break;
self._running = true; // asynch flag
var res = next(self._success, self._error);
if (res && (res.then || res.promise)) {
//console.log("forceHandle : gt promise as result : ",res)
deep.when(res)
.done(function (res) {
//console.log("forceHandle : promise resolved : ",res)
if (typeof res !== 'undefined') {
self._success = (res instanceof Error) ? null : res;
self._error = (res instanceof Error) ? res : null;
}
self._running = false; // asynch flag
if (!self._executing) // real asynch event
self._forceHandle();
})
.fail(function (e) {
self._running = false; // asynch flag
self._success = null;
self._error = e;
if (!self._executing) // real asynch event
self._forceHandle();
});
} else {
self._running = false;
//console.log("deep force queue : res : ",res)
if (typeof res !== 'undefined') {
self._success = (res instanceof Error) ? null : res;
self._error = (res instanceof Error) ? res : null;
}
}
} catch (e) {
var msg = "Internal chain error : rethrow ? " + self._rethrow;
console.error(msg, e);
deep.utils.dumpError(e);
if (self.rethrow)
throw e;
self._success = null;
self._error = e;
self._running = false; // asynch flag
//self._executing = false;
//return forceHandle.call(this);
} finally {
if (previousContext !== self._context) {
if (self._context && self._context.suspend)
self._context.suspend();
if (previousContext && previousContext.resume)
previousContext.resume();
deep.context = previousContext;
}
if (self.oldQueue) {
self._queue = self._queue.concat(self.oldQueue);
delete self.oldQueue;
}
}
}
self._executing = false;
}
}
function createImmediatePromise(result) {
//console.log("deep.createImmediatePromise : ", result instanceof Error)
var prom = new deep.Promise();
return prom._start(result);
}
deep.promise = function deepPromise(arg) {
//console.log("deep.promise : ", arg)
if (typeof arg === "undefined" || arg === null)
return createImmediatePromise(arg);
if (typeof arg.then === 'function') //any promise compliant object
{
if (arg._deep_promise_)
return arg;
//console.log("doing simple promise (no promise and then is present) on : ", arg);
var def = deep.Deferred();
arg.then(function (s) {
def.resolve(s);
}, function (e) {
def.reject(e);
})
return def.promise();
}
if (typeof arg.promise === "function") // deep.Deferred, deep.Chain and jquery deferred case
return arg.promise();
if (typeof arg.promise === 'object')
return arg.promise;
return createImmediatePromise(arg);
}
deep.promise.immediate = createImmediatePromise;
/**
* return a promise that will be fullfilled when arg are ready (resolve or immediat)
* @for deep
* @static
* @method when
* @param {Object} arg an object to waiting for
* @return {deep.Promise} a promise
*/
deep.when = deep.promise;
/**
* return a promise that will be fullfilled when all args are ready (resolve or immediat)
* @for deep
* @static
* @method all
* @param {Object} arg an array of objects to waiting for
* @return {deep.Promise} a promise
*/
deep.all = function deepAll() {
var arr = [];
for (var i in arguments)
arr = arr.concat(arguments[i]);
if (arr.length === 0)
return createImmediatePromise([]);
var def = deep.Deferred();
var count = arr.length;
var c = 0,
d = -1;
var res = [];
var rejected = false;
//console.log("deep.all : try : ",arr)
arr.forEach(function (a) {
if (def.rejected)
return;
var i = d + 1;
if (!a || (!a.then && !a.promise)) {
if (a instanceof Error) {
rejected = true;
if (!def.rejected && !def.resolved && !def.canceled)
def.reject(a);
return;
}
res[i] = a;
c++;
//console.log("deep.all res : ",res)
if (c == count)
def.resolve(res);
} else
deep.when(a).then(function (r) {
if (r instanceof Error) {
if (!def.rejected && !def.resolved && !def.canceled)
def.reject(r);
return;
}
res[i] = r;
c++;
//console.log("deep.all res : ",res)
if (c == count)
def.resolve(res);
}, function (error) {
if (!def.rejected && !def.resolved && !def.canceled)
def.reject(error);
});
d++;
});
return def.promise();
};
//_____________________________________________________________________ DEFERRED
/**
* A deep implementation of Deferred object (see promise on web)
* @class deep.Deferred
* @constructor
*/
deep.Deferred = function deepDeferred() {
if (!(this instanceof deep.Deferred))
return new deep.Deferred();
this._context = deep.context;
this._promises = [];
this._deep_deferred_ = true;
return this;
};
deep.Deferred.prototype = {
_deep_deferred_: true,
_promises: null,
rejected: false,
resolved: false,
canceled: false,
_success: null,
_error: null,
/**
* resolve the Deferred and so the associated promise
* @method resolve
* @param {Object} argument the resolved object injected in promise
* @return {deep.Deferred} this
*/
resolve: function resolveDef(argument) {
//console.log("deep.Deferred.resolve : ", argument);
if (this.rejected || this.resolved || this.canceled)
throw new Error("DeepDeferred (resolve) has already been ended ! could not recolve anymore.");
if (argument instanceof Error)
return this.reject(argument);
this._success = argument;
this.resolved = true;
this._promises.forEach(function (promise) {
promise._start(argument);
});
},
/**
* reject the Deferred and so the associated promise
* @method reject
* @param {Object} argument the rejected object injected in promise
* @return {deep.Deferred} this
*/
reject: function rejectDef(argument) {
// console.log("DeepDeferred.reject");
if (this.rejected || this.resolved || this.canceled)
throw new Error("DeepDeferred has already been ended ! could not reject anymore.");
this._error = argument;
this.rejected = true;
this._promises.forEach(function (promise) {
promise._start(null, argument);
});
},
/**
* return a promise for this deferred
* @method promise
* @return {deep.Promise}
*/
promise: function promiseDef() {
var prom = new deep.Promise();
//console.log("deep2.Deffered.promise : ", prom, " r,r,c : ", this.rejected, this.resolved, this.canceled)
if (this.resolved || this.rejected || this.canceled)
return prom._start(this._success, this._error);
this._promises.push(prom);
return prom;
}
};
deep.Promise = function deepPromiseConstructor(options) {
options = options || {};
this._context = deep.context;
this._queue = [];
this._deep_promise_ = true;
this._running = false;
this._executing = false;
this._initialised = false;
this._rethrow = (typeof options.rethrow !== "undefined") ? options.rethrow : deep.rethrow;
};
deep.Promise.prototype = {
_forceHandle: forceHandle,
_queue: null,
_success: null,
_error: null,
_running: false,
_executing: false,
_initialised: false,
_start: function chainStart(s, e) {
this._initialised = true;
this._success = (s instanceof Error) ? null : s;
this._error = (s instanceof Error) ? s : e;
this._forceHandle();
return this;
},
catchError: function (arg) {
var self = this;
if (self._initialised) {
var func = function catchErrorHandler(s, e) {
self._rethrow = (typeof arg !== 'undefined') ? !arg : false;
};
addInChain.apply(this, [func]);
} else
self._rethrow = (typeof arg !== 'undefined') ? !arg : false;
return this;
},
pushHandlerTo: function (array) {
var self = this;
if (self._initialised) {
var func = function (s, e) {
array.push(self);
};
addInChain.apply(this, [func]);
} else
array.push(self);
return this;
},
condition: function (cond, manager) {
/*
equivalent to (without loading manager if needed)
.always(function(s,e){
if(cond)
manager.apply(self)
})
.condition(deep.mode.dev, "dev::/dumpError")
deep(1)
.condition(deep.mode.dev, function(){
this.fail(function(e){
// handle error for dev
})
})
.each("swig::./items.tpl", req.accept.contain("html"))
*/
var self = this;
var func = function (s, e) { // WARNING : it's an always
if(typeof cond === 'function')
cond = cond();
if(!cond)
return;
var applyCondition = function(manager)
{
self.oldQueue = self._queue;
self._queue = [];
var res = manager.call(self, s, e);
if (res === self)
return;
return res;
}
if (typeof manager === 'string')
return deep.when(deep.get(manager))
.done(function (manager){
if(cond)
return applyCondition(manager);
});
return applyCondition(manager);
};
addInChain.call(this, func);
return this;
},
done: function chainDone(callBack) {
if(!callBack)
return this._success;
var self = this;
var func = function chainDoneHandle(s, e)
{
//console.log("deep.done : ",s,e)
self.oldQueue = self._queue;
self._queue = [];
var a = callBack.apply(self, [s]);
if (a === self)
return;
return a;
};
func._isDone_ = true;
return addInChain.apply(this, [func]);
},
fail: function chainFail(callBack) {
if(!callBack)
return this._error;
var self = this;
var func = function chainFailHandle(s, e) {
self.oldQueue = self._queue;
self._queue = [];
var a = callBack.apply(self, [e]);
if (a === self)
return;
return a;
};
func._isFail_ = true;
return addInChain.apply(this, [func]);
},
always: function chainAlways(callBack)
{
var self = this;
var func = function chainAlwaysHandle(s, e) {
self.oldQueue = self._queue;
self._queue = [];
var a = callBack.apply(self, [s, e]);
if (a === self)
return;
return a;
};
return addInChain.apply(this, [func]);
},
then: function chainThen(successCallBack, errorCallBack)
{
if (successCallBack)
this.done(successCallBack);
if (errorCallBack)
this.fail(errorCallBack);
return this;
},
// __________________________________________________ LOG
/**
*
* log any provided arguments.
* If no arguments provided : will log current success or error state.
*
* transparent true
*
* @method log
* @return {deep.Chain} this
* @chainable
*/
log: function chainLog() {
var self = this;
var args = Array.prototype.slice.call(arguments);
var func = function chainLogHandle(s, e) {
if (args.length === 0) {
if (e)
if (deep.debug)
deep.utils.dumpError(e)
else if (e.report)
args.push("deep.log : error : (" + e.status + "): ", e.message, e.report);
else
args.push("deep.log : error : (" + e.status + "): ", e.message);
else
args.push("deep.log : success : ", s);
}
args.forEach(function (a) {
console.log(a);
});
};
return addInChain.apply(this, [func]);
},
/**
* will wait xxxx ms before contiuing chain
*
* transparent true
*
*
* @chainable
* @method delay
* @param {number} ms
* @return {deep.Chain} this
*/
delay: function chainDelay(ms) {
var self = this;
var func = function (s, e) {
//console.log("deep.delay : ", ms)
var def = deep.Deferred();
setTimeout(function () {
console.log("deep.delay.end : ", ms);
def.resolve(undefined);
}, ms);
return def.promise();
};
return addInChain.apply(this, [func]);
},
context:function (key, val) {
var self = this;
var create = function (s, e) {
if(!self._contextCopied)
deep.context = self._context = deep.utils.simpleCopy(self._context);
self._contextCopied = true;
self._context[key] = val;
};
if(!val)
{
if(key)
return self._context[key];
return self._context;
}
create._isDone_ = true;
return addInChain.call(this, create);
},
logContext: function (key) {
var self = this;
var func = function chainLogHandle(s, e) {
if(key)
console.log("deep.chain.context : ", self._context[key]);
else
console.log("deep.chain.context : ", self._context);
};
return addInChain.apply(this, [func]);
}
};
deep.BaseChain = function BaseChainConstructor(options) {
options = options || {};
this._rethrow = (typeof options.rethrow !== "undefined") ? options.rethrow : deep.rethrow;
this._deep_chain_ = true;
this._context = options._context || deep.context;
this._queue = [];
this._queried = options._queried;
this._nodes = options._nodes; // || [deep.Querier.createRootNode(this._value, options.schema, options)];
this._success = options._success || null;
this._error = options._error || null;
this.positions = [];
this._queried = false;
this.deferred = null;//deep.Deferred();
};
function cloneHandler(handler, cloneValues) {
//console.log("cloneHandler : ", handler, cloneValues);
var newRes = [];
if (cloneValues)
newRes = newRes.concat(handler._nodes);
var newHandler = new deep.Chain({
_root: handler._root,
_rethrow: handler.rethrow,
_nodes: newRes,
_queried: handler._queried,
_error: handler._error,
_context: handler._context,
_success: handler._success
});
newHandler._initialised = true;
return newHandler;
}
var brancher = function brancher(handler) {
var self = this;
var brancher = {
branches: [],
branch: function () {
if(this._ended)
throw deep.errors.Chain("Branching failed : brancher has already bean ended. Could not add branches any more.")
var cloned = cloneHandler(handler, true);
this.branches.push(cloned);
return cloned;
},
promise: function () {
this._ended = true;
return deep.all(this.branches);
}
};
return brancher;
};
deep.BaseChain.prototype = {
_nodes: null,
promise: function () {
if(!this.deferred)
this.deferred = deep.Deferred();
if (this._initialised && this._queue.length === 0 && (!this.oldQueue || this.oldQueue.length === 0) && !this._running && !this._executing)
if (!this._error)
this.deferred.resolve(this._success);
else
this.deferred.reject(this._error);
return this.deferred.promise();
},
_forceHandle: function chainForce() {
var self = this;
if (this.deferred && (self.deferred.rejected || self.deferred.resolved || self.deferred.canceled))
throw deep.errors.Internal("chain has already been ended ! could'nt execute it further.");
forceHandle.apply(this);
if(!this.deferred)
return;
if (self._queue.length === 0 && !self._running)
if (self._error)
self.deferred.reject(self._error);
else
self.deferred.resolve(self._success);
},
/**
*
* log current chain entries with optional title
*
* full option means print full entry in place of just entry.value
* pretty option means print pretty json (indented)
*
* transparent true
*
* @method logValues
* @chainable
* @param title (optional) the title you want
* @param options (optional) could contain : 'full':true|false, 'pretty':true|false
* @return {deep.Chain} this
*/
logValues: function chainLogValues(title, options) {
var self = this;
options = options || {};
var func = function (success, error) {
console.log(title || "deep.logValues : ", " (" + self._nodes.length + " values)");
self._nodes.forEach(function (e) {
var val = e;
var entry = null;
if (e.value) {
entry = e.value._deep_entry;
delete e.value._deep_entry;
}
if (!options.full)
val = e.value;
if (options.pretty)
val = JSON.stringify(val, null, ' ');
console.log("\t- entry : (" + e.path + ") : ", val);
if (entry && e.value)
e.value._deep_entry = entry;
});
};
return addInChain.apply(this, [func]);
},
/**
* wait promise resolution or rejection before continuing chain
*
* asynch
* transparent false
*
* @method when
* @param {deep.Promise} prom the promise to waiting for
* @chainable
* @return {deep.Chain}
*/
when: function (prom) {
var self = this;
var func = function (s, e) {
return prom;
};
func._isDone_ = true;
return addInChain.apply(this, [func]);
},
//_____________________________________________________________ BRANCHES
/**
* asynch handler for chain branches creation
*
* if you return the branches function (the branch creator) : the chain will wait until all the branches are done before continuing
*
* Inject function result in chain as success or error.
*
* @example
* deep().branches( function(branches)
* {
* branches.branch().query(...).load().log()
* branches.branch().query(...).post().log();
* //...
* return branches;
* });
*
* // if you want to return a subset of branches promises :
* // you could use deep.all([array_of_promises]) :
*
* var branch = branches.branch().myChain()...;
* //...
* return deep.all([deep.promise(branch), ...]);
*
* @method branches
* @async
* @chainable
* @param {Function} func the callback that will receive the brancher (see above)
* @return {deep.Chain} this
*/
branches: function chainBranches(func) {
var self = this;
var create = function (s, e) {
self.oldQueue = self.callQueue;
self._queue = [];
var a = func.call(self, brancher(self));
if (a === self)
return;
return a;
};
create._isDone_ = true;
return addInChain.call(this, create);
}
}
deep.Chain = function ChainConstructor(options) {
deep.BaseChain.call(this, options);
}
deep.Chain.prototype = {};
deep.utils.bottom(deep.Promise.prototype, deep.BaseChain.prototype);
deep.utils.bottom(deep.BaseChain.prototype, deep.Chain.prototype);
deep.Chain.addHandle = function addChainHandle(name, func) {
deep.Chain.prototype[name] = func;
return deep.Chain;
}
//__________________________________________________________ HANDLES
var fullAPI = {
/**
* will interpret entries values with context
* @example
* deep("hello { name }").interpret({ name:"john" }).val();
* //will provide "hello john".
* deep({
* msg:"hello { name }"
* })
* .query("./msg")
* .interpret({ name:"john" })
* .logValues()
* .equal("hello john");
*
* @method interpret
* @chainable
* @param {object} context the context to inject in strings
* @return {deep.Chain} this
*/
interpret: function chainInterpret(context) {
var self = this;
var func = function () {
var applyContext = function (context) {
return deep.chain.transform(self, function (v) {
return deep.utils.interpret(v, context);
});
}
if (typeof context === 'string')
return deep.when(deep.get(context)).done(applyContext)
else
return applyContext(context);
};
func._isDone_ = true;
addInChain.apply(this, [func]);
return this;
},
//____________________________________________________________________ LOAD
/**
* will seek in entries after any retrievable string OR executable functions : and will replace references by loaded/returned content.
*
* if context is provided : will try to 'interpret' (see .interpret) strings before retrieving them.
*
* Chain Success injection : array of loaded results
*
* @method deepLoad
* @param {object} context (optional) a context to interpret strings before retrieving
* @chainable
* @return {deep.Chain} this
*/
deepLoad: function chainDeepLoad(context, destructive) {
var self = this;
if(typeof destructive === 'undefined')
destructive = false;
var func = function (s, e) {
var res = [];
var doDeepLoad = function (toLoad) {
if (typeof toLoad.value === 'string') {
var val = toLoad.value;
if (context)
val = deep.utils.interpret(val, context);
// console.log("deepLoad : will get : ", val);
return deep.when(deep.get(val, {
//entry: toLoad,
//resultType:"full"
}))
.done(function (s) {
// console.log("deepLoad.get res : ", s);
return s;//s.value;
});
} else if (typeof toLoad.value === 'function') {
if (toLoad.ancestor)
toLoad.ancestor.value[toLoad.key]();
else
return toLoad.value();
} else
return toLoad.value;
}
var toLoads = [];
self._nodes.forEach(function (node) {
var e = node;
if(!destructive && !deep.destructiveLoad)
e = deep.utils.copy(node.value);