forked from techfort/LokiJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.d.ts
More file actions
2097 lines (1831 loc) · 79.3 KB
/
index.d.ts
File metadata and controls
2097 lines (1831 loc) · 79.3 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
/**
* LokiJS
* A lightweight document oriented javascript database
* @author Joe Minichino <[email protected]>
*/
/** comparison operators
* a is the value in the collection
* b is the query value
*/
declare var LokiOps: {
$eq(a: any, b: any): boolean;
// abstract/loose equality
$aeq(a: any, b: any): boolean;
$ne(a: any, b: any): boolean;
// date equality / loki abstract equality test
$dteq(a: any, b: any): boolean;
$gt(a: any, b: any): boolean;
$gte(a: any, b: any): boolean;
$lt(a: any, b: any): boolean;
$lte(a: any, b: any): boolean;
/** ex : coll.find({'orderCount': {$between: [10, 50]}}); */
$between(a: any, vals: any /* [any, any]*/): boolean;
$jgt(a: any, b: any): boolean;
$jgte(a: any, b: any): boolean;
$jlt(a: any, b: any): boolean;
$jlte(a: any, b: any): boolean;
$jbetween(a: any, vals: any /* [any, any]*/): boolean;
$in(a: any, b: any): boolean;
$nin(a: any, b: any): boolean;
$keyin(a: any, b: any): boolean;
$nkeyin(a: any, b: any): boolean;
$definedin(a: any, b: any): boolean;
$undefinedin(a: any, b: any): boolean;
$regex(a: any, b: any): boolean;
$containsString(a: any, b: any): boolean;
$containsNone(a: any, b: any): boolean;
$containsAny(a: any, b: any): boolean;
$contains(a: any, b: any): boolean;
$type(a: any, b: any): boolean;
$finite(a: any, b: any): boolean;
$size(a: any, b: any): boolean;
$len(a: any, b: any): boolean;
$where(a: any, b: any): boolean;
// 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(a: any, b: any): boolean;
$and(a: any, b: any): boolean;
$or(a: any, b: any): boolean;
};
declare type LokiOps = typeof LokiOps;
/** if an op is registered in this object, our 'calculateRange' can use it with our binary indices.
* if the op is registered to a function, we will run that function/op as a 2nd pass filter on results.
* those 2nd pass filter functions should be similar to LokiOps functions, accepting 2 vals to compare.
*/
declare let indexedOps: {
$eq: LokiOps['$eq'];
$aeq: true;
$dteq: true;
$gt: true;
$gte: true;
$lt: true;
$lte: true;
$in: true;
$between: true;
};
type PartialModel<E, T> = { [P in keyof E]?: T | E[P] };
type LokiQuery<E> = PartialModel<E & { $and: any; $or: any }, { [Y in keyof LokiOps]?: any }>;
interface LokiObj {
$loki: number;
meta: {
created: number; // Date().getTime()
revision: number;
updated: number; // Date().getTime()
version: number;
};
}
/**
* 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
*/
declare class LokiEventEmitter {
/**
* @prop events - a hashmap, with each property being an array of callbacks
*/
public events: { [eventName: string]: ((...args: any[]) => any)[] };
/**
* @prop 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
*/
public asyncListeners: boolean;
/**
* on(eventName, listener) - adds a listener to the queue of callbacks associated to an event
* @param eventName - the name(s) of the event(s) to listen to
* @param listener - callback function of listener to attach
* @returns the index of the callback in the array of listeners for a particular event
*/
on<F extends (...args: any[]) => any>(eventName: string | string[], listener: F): F;
/**
* 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 eventName - the name of the event
* @param data - optional object passed with the event
*/
emit(eventName: string, data?: any, arg?: any): void;
/**
* Alias of LokiEventEmitter.prototype.on
* addListener(eventName, listener) - adds a listener to the queue of callbacks associated to an event
* @param eventName - the name(s) of the event(s) to listen to
* @param listener - callback function of listener to attach
* @returns the event listener added
*/
public addListener: LokiEventEmitter['on'];
/**
* removeListener() - removes the listener at position 'index' from the event 'eventName'
* @param eventName - the name(s) of the event(s) which the listener is attached to
* @param listener - the listener callback function to remove from emitter
*/
public removeListener(eventName: string | string[], listener: (...args: any[]) => any): void;
}
interface LokiConstructorOptions {
verbose: boolean;
env: 'NATIVESCRIPT' | 'NODEJS' | 'CORDOVA' | 'BROWSER' | 'NA';
}
interface LokiConfigOptions {
adapter: LokiPersistenceAdapter | null;
autoload: boolean;
autoloadCallback: (err: any) => void;
autosave: boolean;
autosaveCallback: (err?: any) => void;
autosaveInterval: string | number;
persistenceMethod: 'fs' | 'localStorage' | 'memory' | null;
destructureDelimiter: string;
serializationMethod: 'normal' | 'pretty' | 'destructured' | null;
throttledSaves: boolean;
}
type DeserializeOptions =
| { partitioned?: boolean; delimited: false; delimiter?: string; partition?: number }
| { partitioned?: boolean; delimited?: true; delimiter: string; partition?: number };
interface ThrottledSaveDrainOptions {
recursiveWait: boolean;
recursiveWaitLimit: boolean;
recursiveWaitLimitDuration: number;
started: number;
}
interface Transform {
type:
| 'find'
| 'where'
| 'simplesort'
| 'compoundsort'
| 'sort'
| 'limit'
| 'offset'
| 'map'
| 'eqJoin'
| 'mapReduce'
| 'update'
| 'remove';
value?: any;
property?: string;
desc?: boolean;
dataOptions?: any;
joinData?: any;
leftJoinKey?: any;
rightJoinKey?: any;
mapFun?: any;
mapFunction?: any;
reduceFunction?: any;
}
/**
* Loki: The main database class
* @implements LokiEventEmitter
*/
declare class Loki extends LokiEventEmitter {
collections: Collection<any>[];
options: Partial<LokiConstructorOptions> & LokiConfigOptions & Partial<ThrottledSaveDrainOptions>;
filename: string;
name?: string;
databaseVersion: number;
engineVersion: number;
autosave: boolean;
/**
* A flag that determines whether the autosave functionality should be ignored.
* If set to true, the autosave operation will be bypassed.
*/
ignoreAutosave: boolean;
/**
* A boolean flag indicating whether the database should be serialized
* before saving. When set to true, the database content is converted
* to a serialized format to ensure data integrity during storage.
*/
serializeDatabaseBeforeSave: boolean;
autosaveInterval: number;
autosaveHandle: number | null;
persistenceAdapter: LokiPersistenceAdapter | null | undefined;
persistenceMethod: 'fs' | 'localStorage' | 'memory' | 'adapter' | null | undefined;
throttledCallbacks: ((err?: any) => void)[];
throttledSavePending: boolean;
throttledSaves: boolean;
verbose: boolean;
ENV: 'NATIVESCRIPT' | 'NODEJS' | 'CORDOVA' | 'BROWSER' | 'NA';
/**
* @param filename - name of the file to be saved to
* @param options - (Optional) config options object
* @param options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA'
* @param [options.verbose=false] - enable console output
* @param [options.autosave=false] - enables autosave
* @param [options.autosaveInterval=5000] - time interval (in milliseconds) between saves (if dirty)
* @param [options.autoload=false] - enables autoload on loki instantiation
* @param options.autoloadCallback - user callback called after database load
* @param options.adapter - an instance of a loki persistence adapter
* @param [options.serializationMethod='normal'] - ['normal', 'pretty', 'destructured']
* @param options.destructureDelimiter - string delimiter used for destructured serialization
* @param [options.throttledSaves=true] - debounces multiple calls to to saveDatabase reducing number of disk I/O operations
and guaranteeing proper serialization of the calls.
*/
constructor(
filename: string,
options?: Partial<LokiConstructorOptions> & Partial<LokiConfigOptions> & Partial<ThrottledSaveDrainOptions>,
);
// 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.
public getIndexedAdapter(): any;
/**
* Allows reconfiguring database options
*
* @param options - configuration options to apply to loki db object
* @param options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA'
* @param options.verbose - enable console output (default is 'false')
* @param options.autosave - enables autosave
* @param options.autosaveInterval - time interval (in milliseconds) between saves (if dirty)
* @param options.autoload - enables autoload on loki instantiation
* @param options.autoloadCallback - user callback called after database load
* @param options.adapter - an instance of a loki persistence adapter
* @param options.serializationMethod - ['normal', 'pretty', 'destructured']
* @param options.destructureDelimiter - string delimiter used for destructured serialization
* @param initialConfig - (internal) true is passed when loki ctor is invoking
*/
public configureOptions(
options?: Partial<LokiConfigOptions> & Partial<ThrottledSaveDrainOptions>,
initialConfig?: boolean,
): void;
/**
* Copies 'this' database into a new Loki instance. Object references are shared to make lightweight.
*
* @param options - apply or override collection level settings
* @param options.removeNonSerializable - nulls properties not safe for serialization.
*/
public copy(options?: { removeNonSerializable?: boolean }): Loki;
/**
* Adds a collection to the database.
* @param name - name of collection to add
* @param options - (optional) options to configure collection with.
* @param [options.unique=[]] - array of property names to define unique constraints for
* @param [options.exact=[]] - array of property names to define exact constraints for
* @param [options.indices=[]] - array property names to define binary indexes for
* @param [options.asyncListeners=false] - whether listeners are called asynchronously
* @param [options.disableChangesApi=true] - set to false to enable Changes Api
* @param [options.autoupdate=false] - use Object.observe to update objects automatically
* @param [options.clone=false] - specify whether inserts and queries clone to/from user
* @param [options.cloneMethod='parse-stringify'] - 'parse-stringify', 'jquery-extend-deep', 'shallow, 'shallow-assign'
* @param options.ttlInterval - time interval for clearing out 'aged' documents; not set by default.
* @returns a reference to the collection which was just added
*/
public addCollection<F = any>(name: string, options?: Partial<CollectionOptions<F>>): Collection<F>;
public loadCollection(collection: Collection<any>): void;
/**
* Retrieves reference to a collection by name.
* @param collectionName - name of collection to look up
* @returns Reference to collection in database by that name, or null if not found
*/
public getCollection<F = any>(collectionName: string): Collection<F>;
/**
* Renames an existing loki collection
* @param oldName - name of collection to rename
* @param newName - new name of collection
* @returns reference to the newly renamed collection
*/
public renameCollection(oldName: string, newName: string): Collection<any>;
public listCollections(): Collection<any>[];
/**
* Removes a collection from the database.
* @param collectionName - name of collection to remove
*/
public removeCollection(collectionName: string): void;
public getName(): string;
/**
* serializeReplacer - used to prevent certain properties from being serialized
*/
public serializeReplacer(
key:
| 'autosaveHandle'
| 'persistenceAdapter'
| 'constraints'
| 'ttl'
| 'throttledSavePending'
| 'throttledCallbacks'
| string,
value: any,
): any;
/**
* Serialize database to a string which can be loaded via {@link Loki#loadJSON}
*
* @returns Stringified representation of the loki database.
*/
public serialize(): string;
public serialize(options: { serializationMethod?: 'normal' | 'pretty' }): string;
public serialize(options: { serializationMethod: 'destructured' }): string[];
public serialize(options?: { serializationMethod?: string | null }): string | string[];
public serialize(options?: { serializationMethod?: string | null }): string | string[];
// alias of serialize
public toJson: Loki['serialize'];
/**
* Database level destructured JSON serialization routine to allow alternate serialization methods.
* Internally, Loki supports destructuring via loki "serializationMethod' option and
* the optional LokiPartitioningAdapter class. It is also available if you wish to do
* your own structured persistence or data exchange.
*
* @param options - output format options for use externally to loki
* @param options.partitioned - (default: false) whether db and each collection are separate
* @param options.partition - can be used to only output an individual collection or db (-1)
* @param options.delimited - (default: true) whether subitems are delimited or subarrays
* @param options.delimiter - override default delimiter
*
* @returns A custom, restructured aggregation of independent serializations.
*/
public serializeDestructured(options?: {
delimited?: boolean;
delimiter?: string;
partitioned?: boolean;
partition?: number;
}): string | string[];
/**
* Collection level utility method to serialize a collection in a 'destructured' format
*
* @param [options] - used to determine output of method
* @param [options.delimited] - whether to return single delimited string or an array
* @param [options.delimiter] - (optional) if delimited, this is delimiter to use
* @param [options.collectionIndex] - specify which collection to serialize data for
*
* @returns A custom, restructured aggregation of independent serializations for a single collection.
*/
public serializeCollection(options?: {
delimited?: boolean;
collectionIndex?: number;
delimiter?: string;
}): string | string[];
/**
* Database level destructured JSON deserialization routine to minimize memory overhead.
* Internally, Loki supports destructuring via loki "serializationMethod' option and
* the optional LokiPartitioningAdapter class. It is also available if you wish to do
* your own structured persistence or data exchange.
*
* @param destructuredSource - destructured json or array to deserialize from
* @param [options] - source format options
* @param [options.partitioned=false] - whether db and each collection are separate
* @param [options.partition] - can be used to deserialize only a single partition
* @param [options.delimited=true] - whether subitems are delimited or subarrays
* @param [options.delimiter] - override default delimiter
*
* @returns An object representation of the deserialized database, not yet applied to 'this' db or document array
*/
public deserializeDestructured(destructuredSource: string | string[] | null, options?: DeserializeOptions): any;
/**
* Collection level utility function to deserializes a destructured collection.
*
* @param destructuredSource - destructured representation of collection to inflate
* @param [options] - used to describe format of destructuredSource input
* @param [options.delimited=false] - whether source is delimited string or an array
* @param [options.delimiter] - if delimited, this is delimiter to use (if other than default)
*
* @returns an array of documents to attach to collection.data.
*/
public deserializeCollection(
destructuredSource: string | string[],
options?: { partitioned?: boolean; delimited?: boolean; delimiter?: string },
): any[];
/**
* Inflates a loki database from a serialized JSON string
*
* @param serializedDb - a serialized loki database string
* @param [options] - apply or override collection level settings
* @param [options.serializationMethod] - the serialization format to deserialize
*/
public loadJSON(
serializedDb: string,
options?: { serializationMethod?: 'normal' | 'pretty' | 'destructured' | null } & {
retainDirtyFlags?: boolean;
throttledSaves?: boolean;
[collName: string]: any | { proto?: any; inflate?: (src: object, dest?: object) => void };
},
): void;
/**
* Inflates a loki database from a JS object
*
* @param dbObject - a serialized loki database string
* @param options - apply or override collection level settings
* @param options.retainDirtyFlags - whether collection dirty flags will be preserved
*/
public loadJSONObject(
dbObject: { name?: string; throttledSaves: boolean; collections: Collection<any>[]; databaseVersion: number },
options?: {
retainDirtyFlags?: boolean;
throttledSaves?: boolean;
[collName: string]: any | { proto?: any; inflate?: (src: object, dest?: object) => void };
},
): void;
/**
* Emits the close event. In autosave scenarios, if the database is dirty, this will save and disable timer.
* Does not actually destroy the db.
*
* @param callback - (Optional) if supplied will be registered with close event before emitting.
*/
public close(callback?: (err?: any) => void): void;
/** -------------------------+
| Changes API |
+--------------------------*/
/**
* The Changes API enables the tracking the changes occurred in the collections since the beginning of the session,
* so it's possible to create a differential dataset for synchronization purposes (possibly to a remote db)
*/
/**
* (Changes API) : takes all the changes stored in each
* collection and creates a single array for the entire database. If an array of names
* of collections is passed then only the included collections will be tracked.
*
* @param optional array of collection names. No arg means all collections are processed.
* @returns array of changes
* @see private method createChange() in Collection
*/
public generateChangesNotification(arrayOfCollectionNames?: string[] | null): CollectionChange[];
/**
* (Changes API) - stringify changes for network transmission
* @returns string representation of the changes
*/
public serializeChanges(collectionNamesArray?: string[]): string;
/**
* (Changes API) : clears all the changes in all collections.
*/
public clearChanges(): void;
/**
* Wait for throttledSaves to complete and invoke your callback when drained or duration is met.
*
* @param callback - callback to fire when save queue is drained, it is passed a sucess parameter value
* @param [options] - configuration options
* @param [options.recursiveWait] - (default: true) if after queue is drained, another save was kicked off, wait for it
* @param [options.recursiveWaitLimit] - (default: false) limit our recursive waiting to a duration
* @param [options.recursiveWaitLimitDelay] - (default: 2000) cutoff in ms to stop recursively re-draining
*/
public throttledSaveDrain(callback: (result?: boolean) => void, options?: Partial<ThrottledSaveDrainOptions>): void;
/**
* Internal load logic, decoupled from throttling/contention logic
*
* @param [options] - not currently used (remove or allow overrides?)
* @param [callback] - (Optional) user supplied async callback / error handler
*/
public loadDatabaseInternal(options?: any, callback?: (err?: any, data?: any) => void): void;
/**
* Handles manually loading from file system, local storage, or adapter (such as indexeddb)
* This method utilizes loki configuration options (if provided) to determine which
* persistence method to use, or environment detection (if configuration was not provided).
* To avoid contention with any throttledSaves, we will drain the save queue first.
*
* If you are configured with autosave, you do not need to call this method yourself.
*
* @param [options] - if throttling saves and loads, this controls how we drain save queue before loading
* @param [options.recursiveWait] - (default: true) wait recursively until no saves are queued
* @param [options.recursiveWaitLimit] - (default: false) limit our recursive waiting to a duration
* @param [options.recursiveWaitLimitDelay] - (default: 2000) cutoff in ms to stop recursively re-draining
* @param [callback] - (Optional) user supplied async callback / error handler
* @example
* db.loadDatabase({}, function(err) {
* if (err) {
* console.log("error : " + err);
* }
* else {
* console.log("database loaded.");
* }
* });
*/
public loadDatabase(options?: Partial<ThrottledSaveDrainOptions>, callback?: (err: any) => void): void;
/**
* Internal save logic, decoupled from save throttling logic
*/
public saveDatabaseInternal(callback?: (err: any) => void): void;
/**
* Handles manually saving to file system, local storage, or adapter (such as indexeddb)
* This method utilizes loki configuration options (if provided) to determine which
* persistence method to use, or environment detection (if configuration was not provided).
*
* If you are configured with autosave, you do not need to call this method yourself.
*
* @param [callback] - (Optional) user supplied async callback / error handler
* @example
* db.saveDatabase(function(err) {
* if (err) {
* console.log("error : " + err);
* }
* else {
* console.log("database saved.");
* }
* });
*/
public saveDatabase(callback?: (err?: any) => void): void;
// alias
public save: Loki['saveDatabase'];
/**
* Handles deleting a database from file system, local
* storage, or adapter (indexeddb)
* This method utilizes loki configuration options (if provided) to determine which
* persistence method to use, or environment detection (if configuration was not provided).
*
* @param callback - (Optional) user supplied async callback / error handler
*/
public deleteDatabase(callback: (err?: any, data?: any) => void): void;
public deleteDatabase(options?: null, callback?: (err?: any, data?: any) => void): void;
public deleteDatabase(
options?: ((err?: any, data?: any) => void) | null,
callback?: (err?: any, data?: any) => void,
): void;
/**
* autosaveDirty - check whether any collections are 'dirty' meaning we need to save (entire) database
*
* @returns true if database has changed since last autosave, false if not.
*/
public autosaveDirty(): boolean;
/**
* autosaveClearFlags - resets dirty flags on all collections.
* Called from saveDatabase() after db is saved.
*
*/
public autosaveClearFlags(): void;
/**
* autosaveEnable - begin a javascript interval to periodically save the database.
*
* @param [options] - not currently used (remove or allow overrides?)
* @param [callback] - (Optional) user supplied async callback
*/
public autosaveEnable(options?: any, callback?: (err?: any) => void): void;
/**
* autosaveDisable - stop the autosave interval timer.
*/
public autosaveDisable(): void;
public closeDatabase(): void;
}
/* ------------------+
| PERSISTENCE |
-------------------*/
/** there are two build in persistence adapters for internal use
* fs for use in Nodejs type environments
* localStorage for use in browser environment
* defined as helper classes here so its easy and clean to use
*/
interface LokiPersistenceAdapter {
mode?: string;
loadDatabase(dbname: string, callback: (value: any) => void): void;
deleteDatabase?(dbnameOrOptions: any, callback: (err?: Error | null, data?: any) => void): void;
exportDatabase?(dbname: string, dbref: Loki, callback: (err: Error | null) => void): void;
saveDatabase?(dbname: string, dbstring: any, callback: (err?: Error | null) => void): void;
closeDatabase?(): void;
}
/**
* In in-memory persistence adapter for an in-memory database.
* This simple 'key/value' adapter is intended for unit testing and diagnostics.
*
* @param [options] - memory adapter options
* @param [options.asyncResponses=false] - whether callbacks are invoked asynchronously
* @param [options.asyncTimeout=50] - timeout in ms to queue callbacks
* @constructor LokiMemoryAdapter
*/
declare class LokiMemoryAdapter implements LokiPersistenceAdapter {
hashStore: { [name: string]: { savecount: number; lastsave: Date; value: string } };
options: { asyncResponses?: boolean; asyncTimeout?: number };
constructor(options?: { asyncResponses?: boolean; asyncTimeout?: number });
/**
* Loads a serialized database from its in-memory store.
* (Loki persistence adapter interface function)
*
* @param dbname - name of the database (filename/keyname)
* @param callback - adapter callback to return load result to caller
*/
public loadDatabase(dbname: string, callback: (value: any) => void): void;
/**
* Saves a serialized database to its in-memory store.
* (Loki persistence adapter interface function)
*
* @param dbname - name of the database (filename/keyname)
* @param callback - adapter callback to return load result to caller
*/
public saveDatabase(dbname: string, dbstring: any, callback: (err?: Error | null) => void): void;
/**
* Deletes a database from its in-memory store.
*
* @param dbname - name of the database (filename/keyname)
* @param callback - function to call when done
*/
public deleteDatabase(dbname: string, callback: (err?: Error | null) => void): void;
}
interface PageIterator {
collection: number;
pageIndex: number;
docIndex: number;
}
/**
* An adapter for adapters. Converts a non reference mode adapter into a reference mode adapter
* which can perform destructuring and partioning. Each collection will be stored in its own key/save and
* only dirty collections will be saved. If you turn on paging with default page size of 25megs and save
* a 75 meg collection it should use up roughly 3 save slots (key/value pairs sent to inner adapter).
* A dirty collection that spans three pages will save all three pages again
* Paging mode was added mainly because Chrome has issues saving 'too large' of a string within a
* single indexeddb row. If a single document update causes the collection to be flagged as dirty, all
* of that collection's pages will be written on next save.
*
* @param adapter - reference to a 'non-reference' mode loki adapter instance.
* @param options - configuration options for partitioning and paging
* @param [options.paging] - (default: false) set to true to enable paging collection data.
* @param [options.pageSize] - (default : 25MB) you can use this to limit size of strings passed to inner adapter.
* @param [options.delimiter] - allows you to override the default delimeter
* @constructor LokiPartitioningAdapter
*/
declare class LokiPartitioningAdapter implements LokiPersistenceAdapter {
mode: string;
dbref: Loki | null;
dbname: string;
adapter: LokiPersistenceAdapter | null;
options: { paging?: boolean; pageSize?: number; delimiter?: string };
pageIterator: PageIterator | {};
dirtyPartitions: number[] | undefined;
constructor(adapter: LokiPersistenceAdapter, options?: { paging?: boolean; pageSize?: number; delimiter?: string });
/**
* Loads a database which was partitioned into several key/value saves.
* (Loki persistence adapter interface function)
*
* @param dbname - name of the database (filename/keyname)
* @param callback - adapter callback to return load result to caller
*/
public loadDatabase(dbname: string, callback: (dbOrErr: Loki | null | Error) => void): void;
/**
* Used to sequentially load each collection partition, one at a time.
*
* @param partition - ordinal collection position to load next
* @param callback - adapter callback to return load result to caller
*/
public loadNextPartition(partition: number, callback: () => void): void;
/**
* Used to sequentially load the next page of collection partition, one at a time.
*
* @param callback - adapter callback to return load result to caller
*/
public loadNextPage(callback: () => void): void;
/**
* Saves a database by partioning into separate key/value saves.
* (Loki 'reference mode' persistence adapter interface function)
*
* @param dbname - name of the database (filename/keyname)
* @param dbref - reference to database which we will partition and save.
* @param callback - adapter callback to return load result to caller
*/
public exportDatabase(dbname: string, dbref: Loki, callback: (err: Error | null) => void): void;
/**
* Helper method used internally to save each dirty collection, one at a time.
*
* @param callback - adapter callback to return load result to caller
*/
public saveNextPartition(callback: (err: Error | null) => void): void;
/**
* Helper method used internally to generate and save the next page of the current (dirty) partition.
*
* @param callback - adapter callback to return load result to caller
*/
public saveNextPage(callback: (err: Error | null) => void): void;
}
/**
* A loki persistence adapter which persists using node fs module
* @constructor LokiFsAdapter
*/
declare class LokiFsAdapter implements LokiPersistenceAdapter {
constructor();
/**
* loadDatabase() - Load data from file, will throw an error if the file does not exist
* @param dbname - the filename of the database to load
* @param callback - the callback to handle the result
*/
public loadDatabase(dbname: string, callback: (data: any | Error) => void): void;
/**
* saveDatabase() - save data to file, will throw an error if the file can't be saved
* might want to expand this to avoid dataloss on partial save
* @param dbname - the filename of the database to load
* @param callback - the callback to handle the result
*/
public saveDatabase(dbname: string, dbstring: string | Uint8Array, callback: (err?: Error | null) => void): void;
/**
* deleteDatabase() - delete the database file, will throw an error if the
* file can't be deleted
* @param dbname - the filename of the database to delete
* @param callback - the callback to handle the result
*/
public deleteDatabase(dbname: string, callback: (err?: Error | null) => void): void;
}
/**
* A loki persistence adapter which persists to web browser's local storage object
* @constructor LokiLocalStorageAdapter
*/
declare class LokiLocalStorageAdapter {
/**
* loadDatabase() - Load data from localstorage
* @param dbname - the name of the database to load
* @param callback - the callback to handle the result
*/
public loadDatabase(dbname: string, callback: (dataOrError: any | Error) => void): void;
/**
* saveDatabase() - save data to localstorage, will throw an error if the file can't be saved
* might want to expand this to avoid dataloss on partial save
* @param dbname - the filename of the database to load
* @param callback - the callback to handle the result
*/
public saveDatabase(dbname: string, dbstring: string, callback: (err?: Error | null) => void): void;
/**
* deleteDatabase() - delete the database from localstorage, will throw an error if it
* can't be deleted
* @param dbname - the filename of the database to delete
* @param callback - the callback to handle the result
*/
public deleteDatabase(dbname: string, callback: (err?: Error | null) => void): void;
}
interface GetDataOptions {
forceClones: boolean;
forceCloneMethod:
| ('parse-stringify' | 'jquery-extend-deep' | 'shallow' | 'shallow-assign' | 'shallow-recurse-objects')
| null;
removeMeta: boolean;
}
interface SimplesortOptions {
desc: boolean;
disableIndexIntersect: boolean;
forceIndexIntersect: boolean;
useJavascriptSorting: boolean;
}
/**
* Resultset class allowing chainable queries. Intended to be instanced internally.
* Collection.find(), Collection.where(), and Collection.chain() instantiate this.
*
* @example
* mycollection.chain()
* .find({ 'doors' : 4 })
* .where(function(obj) { return obj.name === 'Toyota' })
* .data();
*/
declare class Resultset<E> {
collection: Collection<E>;
filteredrows: number[];
filterInitialized: boolean;
/**
* @param collection - The collection which this Resultset will query against.
* @param options
*/
constructor(collection: Collection<E>, options?: any);
/**
* reset() - Reset the resultset to its initial state.
*
* @returns Reference to this resultset, for future chain operations.
*/
public reset(): this;
/**
* toJSON() - Override of toJSON to avoid circular references
*/
public toJSON(): Resultset<E>;
/**
* Allows you to limit the number of documents passed to next chain operation.
* A resultset copy() is made to avoid altering original resultset.
*
* @param qty - The number of documents to return.
* @returns Returns a copy of the resultset, limited by qty, for subsequent chain ops.
*/
public limit(qty: number): Resultset<E>;
/**
* Used for skipping 'pos' number of documents in the resultset.
*
* @param pos - Number of documents to skip; all preceding documents are filtered out.
* @returns Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops.
*/
public offset(pos: number): Resultset<E>;
/**
* copy() - To support reuse of resultset in branched query situations.
*
* @returns Returns a copy of the resultset (set) but the underlying document references will be the same.
*/
public copy(): Resultset<E>;
/**
* Alias of copy()
*/
public branch: Resultset<E>['copy'];
/**
* transform() - executes a named collection transform or raw array of transform steps against the resultset.
*
* @param transform - name of collection transform or raw transform array
* @param parameters - (Optional) object property hash of parameters, if the transform requires them.
* @returns either (this) resultset or a clone of of this resultset (depending on steps)
*/
public transform(transform: string | string[] | Transform[], parameters?: object): Resultset<any>;
/**
* User supplied compare function is provided two documents to compare. (chainable)
* @example
* rslt.sort(function(obj1, obj2) {
* if (obj1.name === obj2.name) return 0;
* if (obj1.name > obj2.name) return 1;
* if (obj1.name < obj2.name) return -1;
* });
*
* @param comparefun - A javascript compare function used for sorting.
* @returns Reference to this resultset, sorted, for future chain operations.
*/
public sort(comparefun: (a: E & LokiObj, b: E & LokiObj) => number): this;
/**
* Simpler, loose evaluation for user to sort based on a property name. (chainable).
* Sorting based on the same lt/gt helper functions used for binary indices.
*
* @param propname - name of property to sort by.
* @param options - boolean to specify if sort is descending, or options object
* @param [options.desc] - whether to sort descending
* @param [options.disableIndexIntersect] - whether we should explicity not use array intersection.
* @param [options.forceIndexIntersect] - force array intersection (if binary index exists).
* @param [options.useJavascriptSorting] - whether results are sorted via basic javascript sort.
* @returns Reference to this resultset, sorted, for future chain operations.
*/
public simplesort(propname: keyof E, options?: boolean | Partial<SimplesortOptions>): this;
/**
* Allows sorting a resultset based on multiple columns.
* @example
* // to sort by age and then name (both ascending)
* rs.compoundsort(['age', 'name']);
* // to sort by age (ascending) and then by name (descending)
* rs.compoundsort(['age', ['name', true]);
*
* @param properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order
* @returns Reference to this resultset, sorted, for future chain operations.
*/
public compoundsort(properties: [keyof E, boolean][]): this;
/**
* findOr() - oversee the operation of OR'ed query expressions.
* OR'ed expression evaluation runs each expression individually against the full collection,
* and finally does a set OR on each expression's results.
* Each evaluation can utilize a binary index to prevent multiple linear array scans.
*
* @param expressionArray - array of expressions
* @returns this resultset for further chain ops.
*/
public findOr(expressionArray: LokiQuery<E>[]): this;
public $or: Resultset<E>['findOr'];
/**
* findAnd() - oversee the operation of AND'ed query expressions.
* AND'ed expression evaluation runs each expression progressively against the full collection,
* internally utilizing existing chained resultset functionality.
* Only the first filter can utilize a binary index.
*
* @param expressionArray - array of expressions
* @returns this resultset for further chain ops.
*/
public findAnd(expressionArray: LokiQuery<E>[]): this;
public $and: Resultset<E>['findAnd'];
/**
* Used for querying via a mongo-style query object.
*
* @param query - A mongo-style query object used for filtering current results.
* @param firstOnly - (Optional) Used by collection.findOne()
* @returns this resultset for further chain ops.
*/
public find(query?: LokiQuery<E>, firstOnly?: boolean): this;
/**
* where() - Used for filtering via a javascript filter function.
*
* @param fun - A javascript function used for filtering current results by.
* @returns this resultset for further chain ops.
*/
public where(fun: (data: E & LokiObj) => boolean): this;
/**
* count() - returns the number of documents in the resultset.
*
* @returns The number of documents in the resultset.
*/
public count(): number;
/**
* Terminates the chain and returns array of filtered documents
*
* @param [options] - allows specifying 'forceClones' and 'forceCloneMethod' options.
* @param [options.forceClones] - Allows forcing the return of cloned objects even when
* the collection is not configured for clone object.
* @param [options.forceCloneMethod] - Allows overriding the default or collection specified cloning method.
* Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign'
* @param [options.removeMeta] - Will force clones and strip $loki and meta properties from documents
*
* @returns Array of documents in the resultset