-
Notifications
You must be signed in to change notification settings - Fork 483
/
Copy pathlokijs.js
4922 lines (4253 loc) · 155 KB
/
lokijs.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
/**
* LokiJS
* @author Joe Minichino <joe.minichino@gmail.com>
*
* A lightweight document oriented javascript database
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define([], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory();
} else {
// Browser globals
root.loki = factory();
}
}(this, function () {
return (function () {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
var Utils = {
copyProperties: function (src, dest) {
var prop;
for (prop in src) {
dest[prop] = src[prop];
}
},
// used to recursively scan hierarchical transform step object for param substitution
resolveTransformObject: function (subObj, params, depth) {
var prop,
pname;
if (typeof depth !== 'number') {
depth = 0;
}
if (++depth >= 10) return subObj;
for (prop in subObj) {
if (typeof subObj[prop] === 'string' && subObj[prop].indexOf("[%lktxp]") === 0) {
pname = subObj[prop].substring(8);
if (params.hasOwnProperty(pname)) {
subObj[prop] = params[pname];
}
} else if (typeof subObj[prop] === "object") {
subObj[prop] = Utils.resolveTransformObject(subObj[prop], params, depth);
}
}
return subObj;
},
// top level utility to resolve an entire (single) transform (array of steps) for parameter substitution
resolveTransformParams: function (transform, params) {
var idx,
clonedStep,
resolvedTransform = [];
if (typeof params === 'undefined') return transform;
// iterate all steps in the transform array
for (idx = 0; idx < transform.length; idx++) {
// clone transform so our scan and replace can operate directly on cloned transform
clonedStep = JSON.parse(JSON.stringify(transform[idx]));
resolvedTransform.push(Utils.resolveTransformObject(clonedStep, params));
}
return resolvedTransform;
}
};
/** Helper function for determining 'less-than' conditions for ops, sorting, and binary indices.
* In the future we might want $lt and $gt ops to use their own functionality/helper.
* Since binary indices on a property might need to index [12, NaN, new Date(), Infinity], we
* need this function (as well as gtHelper) to always ensure one value is LT, GT, or EQ to another.
*/
function ltHelper(prop1, prop2, equal) {
var cv1, cv2;
// 'falsy' and Boolean handling
if (!prop1 || !prop2 || prop1 === true || prop2 === true) {
if ((prop1 === true || prop1 === false) && (prop2 === true || prop2 === false)) {
if (equal) {
return prop1 === prop2;
} else {
if (prop1) {
return false;
} else {
return prop2;
}
}
}
if (prop2 === undefined || prop2 === null || prop1 === true || prop2 === false) {
return equal;
}
if (prop1 === undefined || prop1 === null || prop1 === false || prop2 === true) {
return true;
}
}
if (prop1 === prop2) {
return equal;
}
if (prop1 < prop2) {
return true;
}
if (prop1 > prop2) {
return false;
}
// not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare
cv1 = prop1.toString();
cv2 = prop2.toString();
if (cv1 == cv2) {
return equal;
}
if (cv1 < cv2) {
return true;
}
return false;
}
function gtHelper(prop1, prop2, equal) {
var cv1, cv2;
// 'falsy' and Boolean handling
if (!prop1 || !prop2 || prop1 === true || prop2 === true) {
if ((prop1 === true || prop1 === false) && (prop2 === true || prop2 === false)) {
if (equal) {
return prop1 === prop2;
} else {
if (prop1) {
return !prop2;
} else {
return false;
}
}
}
if (prop1 === undefined || prop1 === null || prop1 === false || prop2 === true) {
return equal;
}
if (prop2 === undefined || prop2 === null || prop1 === true || prop2 === false) {
return true;
}
}
if (prop1 === prop2) {
return equal;
}
if (prop1 > prop2) {
return true;
}
if (prop1 < prop2) {
return false;
}
// not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare
cv1 = prop1.toString();
cv2 = prop2.toString();
if (cv1 == cv2) {
return equal;
}
if (cv1 > cv2) {
return true;
}
return false;
}
function sortHelper(prop1, prop2, desc) {
if (prop1 === prop2) {
return 0;
}
if (ltHelper(prop1, prop2, false)) {
return (desc) ? (1) : (-1);
}
if (gtHelper(prop1, prop2, false)) {
return (desc) ? (-1) : (1);
}
// not lt, not gt so implied equality-- date compatible
return 0;
}
/**
* compoundeval() - helper function for compoundsort(), performing individual object comparisons
*
* @param {array} properties - array of property names, in order, by which to evaluate sort order
* @param {object} obj1 - first object to compare
* @param {object} obj2 - second object to compare
* @returns {integer} 0, -1, or 1 to designate if identical (sortwise) or which should be first
*/
function compoundeval(properties, obj1, obj2) {
var res = 0;
var prop, field;
for (var i = 0, len = properties.length; i < len; i++) {
prop = properties[i];
field = prop[0];
res = sortHelper(obj1[field], obj2[field], prop[1]);
if (res !== 0) {
return res;
}
}
return 0;
}
/**
* dotSubScan - helper function used for dot notation queries.
*
* @param {object} root - object to traverse
* @param {array} paths - array of properties to drill into
* @param {function} fun - evaluation function to test with
* @param {any} value - comparative value to also pass to (compare) fun
*/
function dotSubScan(root, paths, fun, value) {
var arrayRef = null;
var pathIndex, subIndex;
var path;
for (pathIndex = 0; pathIndex < paths.length; pathIndex++) {
path = paths[pathIndex];
// foreach already detected parent was array so this must be where we iterate
if (arrayRef) {
// iterate all sub-array items to see if any yield hits
for (subIndex = 0; subIndex < arrayRef.length; subIndex++) {
if (fun(arrayRef[subIndex][path], value)) {
return true;
}
}
}
// else not yet determined if subarray scan is involved
else {
// if the dot notation is invalid for the current document, then ignore this document
if (typeof root === 'undefined' || root === null || !root.hasOwnProperty(path)) {
return false;
}
root = root[path];
if (root === undefined || root === null) {
return false;
}
if (Array.isArray(root)) {
arrayRef = root;
}
}
}
// made it this far so must be dot notation on non-array property
return fun(root, value);
}
function containsCheckFn(a) {
if (typeof a === 'string' || Array.isArray(a)) {
return function (b) {
return a.indexOf(b) !== -1;
};
} else if (typeof a === 'object') {
return function (b) {
return hasOwnProperty.call(a, b);
};
}
return null;
}
function doQueryOp(val, op) {
for (var p in op) {
if (hasOwnProperty.call(op, p)) {
return LokiOps[p](val, op[p]);
}
}
return false;
}
var LokiOps = {
// comparison operators
// a is the value in the collection
// b is the query value
$eq: function (a, b) {
return a === b;
},
// abstract/loose equality
$aeq: function (a, b) {
return a == b;
},
$ne: function (a, b) {
if (isNaN(b)) {
return !isNaN(a);
}
return a !== b;
},
$dteq: function(a, b) {
if (ltHelper(a, b, false)) {
return false;
}
return !gtHelper(a, b, false);
},
$gt: function (a, b) {
return gtHelper(a, b, false);
},
$gte: function (a, b) {
return gtHelper(a, b, true);
},
$lt: function (a, b) {
return ltHelper(a, b, false);
},
$lte: function (a, b) {
return ltHelper(a, b, true);
},
$in: function (a, b) {
return b.indexOf(a) !== -1;
},
$nin: function (a, b) {
return b.indexOf(a) === -1;
},
$keyin: function (a, b) {
return a in b;
},
$nkeyin: function (a, b) {
return !(a in b);
},
$definedin: function (a, b) {
return b[a] !== undefined;
},
$undefinedin: function (a, b) {
return b[a] === undefined;
},
$regex: function (a, b) {
return b.test(a);
},
$containsString: function (a, b) {
return (typeof a === 'string') && (a.indexOf(b) !== -1);
},
$containsNone: function (a, b) {
return !LokiOps.$containsAny(a, b);
},
$containsAny: function (a, b) {
var checkFn = containsCheckFn(a);
if (checkFn !== null) {
return (Array.isArray(b)) ? (b.some(checkFn)) : (checkFn(b));
}
return false;
},
$contains: function (a, b) {
var checkFn = containsCheckFn(a);
if (checkFn !== null) {
return (Array.isArray(b)) ? (b.every(checkFn)) : (checkFn(b));
}
return false;
},
$type: function (a, b) {
var type = typeof a;
if (type === 'object') {
if (Array.isArray(a)) {
type = 'array';
} else if (a instanceof Date) {
type = 'date';
}
}
return (typeof b !== 'object') ? (type === b) : doQueryOp(type, b);
},
$size: function (a, b) {
if (Array.isArray(a)) {
return (typeof b !== 'object') ? (a.length === b) : doQueryOp(a.length, b);
}
return false;
},
$len: function (a, b) {
if (typeof a === 'string') {
return (typeof b !== 'object') ? (a.length === b) : doQueryOp(a.length, b);
}
return false;
},
$where: function (a, b) {
return b(a) === true;
},
// field-level logical operators
// a is the value in the collection
// b is the nested query operation (for '$not')
// or an array of nested query operations (for '$and' and '$or')
$not: function (a, b) {
return !doQueryOp(a, b);
},
$and: function (a, b) {
for (var idx = 0, len = b.length; idx < len; idx += 1) {
if (!doQueryOp(a, b[idx])) {
return false;
}
}
return true;
},
$or: function (a, b) {
for (var idx = 0, len = b.length; idx < len; idx += 1) {
if (doQueryOp(a, b[idx])) {
return true;
}
}
return false;
}
};
// making indexing opt-in... our range function knows how to deal with these ops :
var indexedOpsList = ['$eq', '$aeq', '$dteq', '$gt', '$gte', '$lt', '$lte'];
function clone(data, method) {
var cloneMethod = method || 'parse-stringify',
cloned;
switch (cloneMethod) {
case "parse-stringify":
cloned = JSON.parse(JSON.stringify(data));
break;
case "jquery-extend-deep":
cloned = jQuery.extend(true, {}, data);
break;
case "shallow":
cloned = Object.create(data.prototype || null);
Object.keys(data).map(function (i) {
cloned[i] = data[i];
});
break;
default:
break;
}
//if (cloneMethod === 'parse-stringify') {
// cloned = JSON.parse(JSON.stringify(data));
//}
return cloned;
}
function cloneObjectArray(objarray, method) {
var i,
result = [];
if (method == "parse-stringify") {
return clone(objarray, method);
}
i = objarray.length-1;
for(;i<=0;i--) {
result.push(clone(objarray[i], method));
}
return result;
}
function localStorageAvailable() {
try {
return (window && window.localStorage !== undefined && window.localStorage !== null);
} catch (e) {
return false;
}
}
/**
* LokiEventEmitter is a minimalist version of EventEmitter. It enables any
* constructor that inherits EventEmitter to emit events and trigger
* listeners that have been added to the event through the on(event, callback) method
*
* @constructor LokiEventEmitter
*/
function LokiEventEmitter() {}
/**
* @prop {hashmap} events - a hashmap, with each property being an array of callbacks
* @memberof LokiEventEmitter
*/
LokiEventEmitter.prototype.events = {};
/**
* @prop {boolean} asyncListeners - boolean determines whether or not the callbacks associated with each event
* should happen in an async fashion or not
* Default is false, which means events are synchronous
* @memberof LokiEventEmitter
*/
LokiEventEmitter.prototype.asyncListeners = false;
/**
* on(eventName, listener) - adds a listener to the queue of callbacks associated to an event
* @param {string} eventName - the name of the event to listen to
* @param {function} listener - callback function of listener to attach
* @returns {int} the index of the callback in the array of listeners for a particular event
* @memberof LokiEventEmitter
*/
LokiEventEmitter.prototype.on = function (eventName, listener) {
var event = this.events[eventName];
if (!event) {
event = this.events[eventName] = [];
}
event.push(listener);
return listener;
};
/**
* emit(eventName, data) - emits a particular event
* with the option of passing optional parameters which are going to be processed by the callback
* provided signatures match (i.e. if passing emit(event, arg0, arg1) the listener should take two parameters)
* @param {string} eventName - the name of the event
* @param {object} data - optional object passed with the event
* @memberof LokiEventEmitter
*/
LokiEventEmitter.prototype.emit = function (eventName, data) {
var self = this;
if (eventName && this.events[eventName]) {
this.events[eventName].forEach(function (listener) {
if (self.asyncListeners) {
setTimeout(function () {
listener(data);
}, 1);
} else {
listener(data);
}
});
} else {
throw new Error('No event ' + eventName + ' defined');
}
};
/**
* removeListener() - removes the listener at position 'index' from the event 'eventName'
* @param {string} eventName - the name of the event which the listener is attached to
* @param {function} listener - the listener callback function to remove from emitter
* @memberof LokiEventEmitter
*/
LokiEventEmitter.prototype.removeListener = function (eventName, listener) {
if (this.events[eventName]) {
var listeners = this.events[eventName];
listeners.splice(listeners.indexOf(listener), 1);
}
};
/**
* Loki: The main database class
* @constructor Loki
* @implements LokiEventEmitter
* @param {string} filename - name of the file to be saved to
* @param {object} options - (Optional) config options object
* @param {string} options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA'
* @param {boolean} options.verbose - enable console output (default is 'false')
* @param {boolean} options.autosave - enables autosave
* @param {int} options.autosaveInterval - time interval (in milliseconds) between saves (if dirty)
* @param {boolean} options.autoload - enables autoload on loki instantiation
* @param {function} options.autoloadCallback - user callback called after database load
* @param {adapter} options.adapter - an instance of a loki persistence adapter
*/
function Loki(filename, options) {
this.filename = filename || 'loki.db';
this.collections = [];
// persist version of code which created the database to the database.
// could use for upgrade scenarios
this.databaseVersion = 1.1;
this.engineVersion = 1.1;
// autosave support (disabled by default)
// pass autosave: true, autosaveInterval: 6000 in options to set 6 second autosave
this.autosave = false;
this.autosaveInterval = 5000;
this.autosaveHandle = null;
this.options = {};
// currently keeping persistenceMethod and persistenceAdapter as loki level properties that
// will not or cannot be deserialized. You are required to configure persistence every time
// you instantiate a loki object (or use default environment detection) in order to load the database anyways.
// persistenceMethod could be 'fs', 'localStorage', or 'adapter'
// this is optional option param, otherwise environment detection will be used
// if user passes their own adapter we will force this method to 'adapter' later, so no need to pass method option.
this.persistenceMethod = null;
// retain reference to optional (non-serializable) persistenceAdapter 'instance'
this.persistenceAdapter = null;
// enable console output if verbose flag is set (disabled by default)
this.verbose = options && options.hasOwnProperty('verbose') ? options.verbose : false;
this.events = {
'init': [],
'loaded': [],
'flushChanges': [],
'close': [],
'changes': [],
'warning': []
};
var getENV = function () {
// if (typeof global !== 'undefined' && (global.android || global.NSObject)) {
// //If no adapter is set use the default nativescript adapter
// if (!options.adapter) {
// var LokiNativescriptAdapter = require('./loki-nativescript-adapter');
// options.adapter=new LokiNativescriptAdapter();
// }
// return 'NATIVESCRIPT'; //nativescript
// }
if (typeof window === 'undefined') {
return 'NODEJS';
}
if (typeof global !== 'undefined' && global.window) {
return 'NODEJS'; //node-webkit
}
if (typeof document !== 'undefined') {
if (document.URL.indexOf('http://') === -1 && document.URL.indexOf('https://') === -1) {
return 'CORDOVA';
}
return 'BROWSER';
}
return 'CORDOVA';
};
// refactored environment detection due to invalid detection for browser environments.
// if they do not specify an options.env we want to detect env rather than default to nodejs.
// currently keeping two properties for similar thing (options.env and options.persistenceMethod)
// might want to review whether we can consolidate.
if (options && options.hasOwnProperty('env')) {
this.ENV = options.env;
} else {
this.ENV = getENV();
}
// not sure if this is necessary now that i have refactored the line above
if (this.ENV === 'undefined') {
this.ENV = 'NODEJS';
}
//if (typeof (options) !== 'undefined') {
this.configureOptions(options, true);
//}
this.on('init', this.clearChanges);
}
// db class is an EventEmitter
Loki.prototype = new LokiEventEmitter();
// experimental support for browserify's abstract syntax scan to pick up dependency of indexed adapter.
// Hopefully, once this hits npm a browserify require of lokijs should scan the main file and detect this indexed adapter reference.
Loki.prototype.getIndexedAdapter = function () {
var adapter;
if (typeof require === 'function') {
adapter = require("./loki-indexed-adapter.js");
}
return adapter;
};
/**
* Allows reconfiguring database options
*
* @param {object} options - configuration options to apply to loki db object
* @param {string} options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA'
* @param {boolean} options.verbose - enable console output (default is 'false')
* @param {boolean} options.autosave - enables autosave
* @param {int} options.autosaveInterval - time interval (in milliseconds) between saves (if dirty)
* @param {boolean} options.autoload - enables autoload on loki instantiation
* @param {function} options.autoloadCallback - user callback called after database load
* @param {adapter} options.adapter - an instance of a loki persistence adapter
* @param {boolean} initialConfig - (internal) true is passed when loki ctor is invoking
* @memberof Loki
*/
Loki.prototype.configureOptions = function (options, initialConfig) {
var defaultPersistence = {
'NODEJS': 'fs',
'BROWSER': 'localStorage',
'CORDOVA': 'localStorage'
},
persistenceMethods = {
'fs': LokiFsAdapter,
'localStorage': LokiLocalStorageAdapter
};
this.options = {};
this.persistenceMethod = null;
// retain reference to optional persistence adapter 'instance'
// currently keeping outside options because it can't be serialized
this.persistenceAdapter = null;
// process the options
if (typeof (options) !== 'undefined') {
this.options = options;
if (this.options.hasOwnProperty('persistenceMethod')) {
// check if the specified persistence method is known
if (typeof (persistenceMethods[options.persistenceMethod]) == 'function') {
this.persistenceMethod = options.persistenceMethod;
this.persistenceAdapter = new persistenceMethods[options.persistenceMethod]();
}
// should be throw an error here, or just fall back to defaults ??
}
// if user passes adapter, set persistence mode to adapter and retain persistence adapter instance
if (this.options.hasOwnProperty('adapter')) {
this.persistenceMethod = 'adapter';
this.persistenceAdapter = options.adapter;
this.options.adapter = null;
}
// if they want to load database on loki instantiation, now is a good time to load... after adapter set and before possible autosave initiation
if (options.autoload && initialConfig) {
// for autoload, let the constructor complete before firing callback
var self = this;
setTimeout(function () {
self.loadDatabase(options, options.autoloadCallback);
}, 1);
}
if (this.options.hasOwnProperty('autosaveInterval')) {
this.autosaveDisable();
this.autosaveInterval = parseInt(this.options.autosaveInterval, 10);
}
if (this.options.hasOwnProperty('autosave') && this.options.autosave) {
this.autosaveDisable();
this.autosave = true;
if (this.options.hasOwnProperty('autosaveCallback')) {
this.autosaveEnable(options, options.autosaveCallback);
} else {
this.autosaveEnable();
}
}
} // end of options processing
// if by now there is no adapter specified by user nor derived from persistenceMethod: use sensible defaults
if (this.persistenceAdapter === null) {
this.persistenceMethod = defaultPersistence[this.ENV];
if (this.persistenceMethod) {
this.persistenceAdapter = new persistenceMethods[this.persistenceMethod]();
}
}
};
/**
* Shorthand method for quickly creating and populating an anonymous collection.
* This collection is not referenced internally so upon losing scope it will be garbage collected.
*
* @example
* var results = new loki().anonym(myDocArray).find({'age': {'$gt': 30} });
*
* @param {Array} docs - document array to initialize the anonymous collection with
* @param {object} options - configuration object, see {@link Loki#addCollection} options
* @returns {Collection} New collection which you can query or chain
* @memberof Loki
*/
Loki.prototype.anonym = function (docs, options) {
var collection = new Collection('anonym', options);
collection.insert(docs);
if(this.verbose)
collection.console = console;
return collection;
};
/**
* Adds a collection to the database.
* @param {string} name - name of collection to add
* @param {object} options - (optional) options to configure collection with.
* @param {array} options.unique - array of property names to define unique constraints for
* @param {array} options.exact - array of property names to define exact constraints for
* @param {array} options.indices - array property names to define binary indexes for
* @param {boolean} options.asyncListeners - default is false
* @param {boolean} options.disableChangesApi - default is true
* @param {boolean} options.autoupdate - use Object.observe to update objects automatically (default: false)
* @param {boolean} options.clone - specify whether inserts and queries clone to/from user
* @param {string} options.cloneMethod - 'parse-stringify' (default), 'jquery-extend-deep', 'shallow'
* @param {int} options.ttlInterval - time interval for clearing out 'aged' documents; not set by default.
* @returns {Collection} a reference to the collection which was just added
* @memberof Loki
*/
Loki.prototype.addCollection = function (name, options) {
var collection = new Collection(name, options);
this.collections.push(collection);
if(this.verbose)
collection.console = console;
return collection;
};
Loki.prototype.loadCollection = function (collection) {
if (!collection.name) {
throw new Error('Collection must have a name property to be loaded');
}
this.collections.push(collection);
};
/**
* Retrieves reference to a collection by name.
* @param {string} collectionName - name of collection to look up
* @returns {Collection} Reference to collection in database by that name, or null if not found
* @memberof Loki
*/
Loki.prototype.getCollection = function (collectionName) {
var i,
len = this.collections.length;
for (i = 0; i < len; i += 1) {
if (this.collections[i].name === collectionName) {
return this.collections[i];
}
}
// no such collection
this.emit('warning', 'collection ' + collectionName + ' not found');
return null;
};
Loki.prototype.listCollections = function () {
var i = this.collections.length,
colls = [];
while (i--) {
colls.push({
name: this.collections[i].name,
type: this.collections[i].objType,
count: this.collections[i].data.length
});
}
return colls;
};
/**
* Removes a collection from the database.
* @param {string} collectionName - name of collection to remove
* @memberof Loki
*/
Loki.prototype.removeCollection = function (collectionName) {
var i,
len = this.collections.length;
for (i = 0; i < len; i += 1) {
if (this.collections[i].name === collectionName) {
var tmpcol = new Collection(collectionName, {});
var curcol = this.collections[i];
for (var prop in curcol) {
if (curcol.hasOwnProperty(prop) && tmpcol.hasOwnProperty(prop)) {
curcol[prop] = tmpcol[prop];
}
}
this.collections.splice(i, 1);
return;
}
}
};
Loki.prototype.getName = function () {
return this.name;
};
/**
* serializeReplacer - used to prevent certain properties from being serialized
*
*/
Loki.prototype.serializeReplacer = function (key, value) {
switch (key) {
case 'autosaveHandle':
case 'persistenceAdapter':
case 'constraints':
return null;
default:
return value;
}
};
/**
* Serialize database to a string which can be loaded via {@link Loki#loadJSON}
*
* @returns {string} Stringified representation of the loki database.
* @memberof Loki
*/
Loki.prototype.serialize = function () {
return JSON.stringify(this, this.serializeReplacer);
};
// alias of serialize
Loki.prototype.toJson = Loki.prototype.serialize;
/**
* Inflates a loki database from a serialized JSON string
*
* @param {string} serializedDb - a serialized loki database string
* @param {object} options - apply or override collection level settings
* @memberof Loki
*/
Loki.prototype.loadJSON = function (serializedDb, options) {
var dbObject;
if (serializedDb.length === 0) {
dbObject = {};
} else {
dbObject = JSON.parse(serializedDb);
}
this.loadJSONObject(dbObject, options);
};
/**
* Inflates a loki database from a JS object
*
* @param {object} dbObject - a serialized loki database string
* @param {object} options - apply or override collection level settings
* @memberof Loki
*/
Loki.prototype.loadJSONObject = function (dbObject, options) {
var i = 0,
len = dbObject.collections ? dbObject.collections.length : 0,
coll,
copyColl,
clen,
j;
this.name = dbObject.name;
// restore database version
this.databaseVersion = 1.0;
if (dbObject.hasOwnProperty('databaseVersion')) {
this.databaseVersion = dbObject.databaseVersion;
}
this.collections = [];
for (i; i < len; i += 1) {
coll = dbObject.collections[i];
copyColl = this.addCollection(coll.name);
copyColl.transactional = coll.transactional;
copyColl.asyncListeners = coll.asyncListeners;
copyColl.disableChangesApi = coll.disableChangesApi;
copyColl.cloneObjects = coll.cloneObjects;
copyColl.cloneMethod = coll.cloneMethod || "parse-stringify";
copyColl.autoupdate = coll.autoupdate;
// load each element individually
clen = coll.data.length;
j = 0;
if (options && options.hasOwnProperty(coll.name)) {
var loader = options[coll.name].inflate ? options[coll.name].inflate : Utils.copyProperties;
for (j; j < clen; j++) {
var collObj = new(options[coll.name].proto)();
loader(coll.data[j], collObj);
copyColl.data[j] = collObj;