/
index.js
1512 lines (1416 loc) · 61.1 KB
/
index.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
// Lodash should probably be a core lib but hey, it's useful!
const {
get: _get,
set: _set,
has: _has,
delete: _delete,
isNil,
isFunction,
isArray,
isObject,
toPath,
merge,
clone,
cloneDeep
} = require('lodash');
// Custom error codes with stack support.
const Err = require('./error.js');
const onChange = require('on-change');
// Native imports
const { resolve, sep } = require('path');
const fs = require('fs');
// Package.json
const pkgdata = require('../package.json');
// Symbols are used to create "private" methods.
// https://medium.com/front-end-hacking/private-methods-in-es6-and-writing-your-own-db-b2e30866521f
const _mathop = Symbol('mathop');
const _check = Symbol('check');
const _validateName = Symbol('validateName');
const _fetchCheck = Symbol('fetchCheck');
const _parseData = Symbol('parseData');
const _readyCheck = Symbol('readyCheck');
const _clone = Symbol('clone');
const _init = Symbol('init');
const _defineSetting = Symbol('_defineSetting');
/**
* A enhanced Map structure with additional utility methods.
* Can be made persistent
* @extends {Map}
*/
class Enmap extends Map {
/**
* Initializes a new Enmap, with options.
* @param {iterable|string} iterable If iterable data, only valid in non-persistent enmaps.
* If this parameter is a string, it is assumed to be the enmap's name, which is a shorthand for adding a name in the options
* and making the enmap persistent.
* @param {Object} [options] Additional options for the enmap. See https://enmap.evie.codes/usage#enmap-options for details.
* @param {string} [options.name] The name of the enmap. Represents its table name in sqlite. If present, the enmap is persistent.
* If no name is given, the enmap is memory-only and is not saved in the database. As a shorthand, you may use a string for the name
* instead of the options (see example).
* @param {boolean} [options.fetchAll] Defaults to `true`. When enabled, will automatically fetch any key that's requested using get,
* or other retrieval methods. This is a "syncroneous" operation, which means it doesn't need any of this promise or callback use.
* @param {string} [options.dataDir] Defaults to `./data`. Determines where the sqlite files will be stored. Can be relative
* (to your project root) or absolute on the disk. Windows users , remember to escape your backslashes!
* @param {string} [options.cloneLevel] Defaults to deep. Determines how objects and arrays are treated when inserting and retrieving from the database.
* See https://enmap.evie.codes/usage#enmap-options for more details on this option.
* @param {boolean} [options.polling] defaults to `false`. Determines whether Enmap will attempt to retrieve changes from the database on a regular interval.
* This means that if another Enmap in another process modifies a value, this change will be reflected in ALL enmaps using the polling feature.
* @param {string} [options.pollingInterval] defaults to `1000`, polling every second. Delay in milliseconds to poll new data from the database.
* The shorter the interval, the more CPU is used, so it's best not to lower this. Polling takes about 350-500ms if no data is found, and time will
* grow with more changes fetched. In my tests, 15 rows took a little more than 1 second, every second.
* @param {boolean} [options.ensureProps] defaults to `true`. If enabled and the value in the enmap is an object, using ensure() will also ensure that
* every property present in the default object will be added to the value, if it's absent. See ensure API reference for more information.
* @param {*} [options.autoEnsure] default is disabled. When provided a value, essentially runs ensure(key, autoEnsure) automatically so you don't have to.
* This is especially useful on get(), but will also apply on set(), and any array and object methods that interact with the database.
* @param {boolean} [options.autoFetch] defaults to `true`. When enabled, attempting to get() a key or do any operation on existing keys (such as array push, etc)
* will automatically fetch the current key value from the database. Keys that are automatically fetched remain in memory and are not cleared.
* @param {Function} [options.serializer] Optional. If a function is provided, it will execute on the data when it is written to the database.
* This is generally used to convert the value into a format that can be saved in the database, such as converting a complete class instance to just its ID.
* This function may return the value to be saved, or a promise that resolves to that value (in other words, can be an async function).
* @param {Function} [options.deserializer] Optional. If a function is provided, it will execute on the data when it is read from the database.
* This is generally used to convert the value from a stored ID into a more complex object.
* This function may return a value, or a promise that resolves to that value (in other words, can be an async function).
* @param {boolean} [options.wal=false] Check out Write-Ahead Logging: https://www.sqlite.org/wal.html
* @example
* const Enmap = require("enmap");
* // Non-persistent enmap:
* const inMemory = new Enmap();
*
* // Named, Persistent enmap with string option
* const myEnmap = new Enmap("testing");
*
* // Enmap that does not fetch everything, but does so on per-query basis:
* const myEnmap = new Enmap({name: "testing", fetchAll: false});
*
* // Enmap that automatically assigns a default object when getting or setting anything.
* const autoEnmap = new Enmap({name: "settings", autoEnsure: { setting1: false, message: "default message"}})
*/
constructor(iterable, options = {}) {
if (typeof iterable === 'string') {
options.name = iterable;
iterable = null;
}
if (!iterable || typeof iterable[Symbol.iterator] !== 'function') {
options = iterable || options;
iterable = null;
}
super();
let cloneLevel;
if (options.cloneLevel) {
const accepted = ['none', 'shallow', 'deep'];
if (!accepted.includes(options.cloneLevel)) throw new Err('Unknown Clone Level. Options are none, shallow, deep. Default is deep.', 'EnmapOptionsError');
cloneLevel = options.cloneLevel; // eslint-disable-line prefer-destructuring
} else {
cloneLevel = 'deep';
}
this[_defineSetting]('cloneLevel', 'String', true, cloneLevel);
this[_defineSetting]('ensureProps', 'Boolean', true, true, options.ensureProps);
// Always needs to be present
this[_defineSetting]('serializer', 'Function', true, (data) => data, options.serializer);
this[_defineSetting]('deserializer', 'Function', true, (data) => data, options.deserializer);
if (options.name) {
const Database = require('better-sqlite3');
this[_defineSetting]('persistent', 'Boolean', false, true);
// Initialize this property, to prepare for a possible destroy() call.
// This is completely ignored in all situations except destroying the enmap.
this[_defineSetting]('isDestroyed', 'Boolean', true, false);
// Define the data directory where the enmap is stored.
if (!options.dataDir) {
if (!fs.existsSync('./data')) {
fs.mkdirSync('./data');
}
}
const dataDir = resolve(process.cwd(), options.dataDir || 'data');
const database = new Database(`${dataDir}${sep}enmap.sqlite`);
// [_defineSetting](name, type, writable, defaultValue [, value]) {
// this[_defineSetting]('all', 'Symbol', false, Symbol('all_records'));
this[_defineSetting]('off', 'Symbol', false, Symbol('option_off'));
this[_defineSetting]('name', 'String', true, options.name);
this[_defineSetting]('dataDir', 'String', false, dataDir);
this[_defineSetting]('fetchAll', 'Boolean', true, true, options.fetchAll);
this[_defineSetting]('database', 'Database', true, database);
this[_defineSetting]('autoFetch', 'Boolean', true, true, options.autoFetch);
this[_defineSetting]('autoEnsure', 'any', true, this.off, options.autoEnsure);
this[_defineSetting]('wal', 'Boolean', true, true, options.wal);
this[_defineSetting]('polling', 'Boolean', true, false, options.polling);
this[_defineSetting]('pollingInterval', 'Number', true, 1000, options.pollingInterval);
this[_defineSetting]('defer', 'Promise', true, new Promise((res) =>
this[_defineSetting]('ready', 'Function', false, res))
);
this[_validateName]();
this[_init](database);
} else {
this[_defineSetting]('name', 'String', true, 'MemoryEnmap');
this[_defineSetting]('isReady', 'Boolean', true, true);
}
if (iterable) {
if (options.name) {
console.log(`Iterable ignored for persistent Enmap ${options.name}`);
} else {
for (const [key, value] of iterable) {
this.set(key, value);
}
}
}
}
/**
* Sets a value in Enmap.
* @param {string} key Required. The key of the element to add to The Enmap.
* @param {*} val Required. The value of the element to add to The Enmap.
* If the Enmap is persistent this value MUST be stringifiable as JSON.
* @param {string} path Optional. The path to the property to modify inside the value object or array.
* Can be a path with dot notation, such as "prop1.subprop2.subprop3"
* @example
* // Direct Value Examples
* enmap.set('simplevalue', 'this is a string');
* enmap.set('isEnmapGreat', true);
* enmap.set('TheAnswer', 42);
* enmap.set('IhazObjects', { color: 'black', action: 'paint', desire: true });
* enmap.set('ArraysToo', [1, "two", "tree", "foor"])
*
* // Settings Properties
* enmap.set('IhazObjects', 'blue', 'color'); //modified previous object
* enmap.set('ArraysToo', 'three', 2); // changes "tree" to "three" in array.
* @returns {Enmap} The enmap.
*/
set(key, val, path = null) {
if (isNil(key) || key.constructor.name !== 'String') {
throw new Err(`Enmap requires keys to be a string. Provided: ${isNil(key) ? 'nil' : key.constructor.name}`, 'EnmapKeyTypeError');
}
key = key.toString();
let data = this.get(key);
const oldValue = super.has(key) ? this[_clone](data) : null;
if (!isNil(path)) {
if (isNil(data)) data = {};
_set(data, path, val);
} else {
data = val;
}
if (isFunction(this.changedCB)) {
this.changedCB(key, oldValue, data);
}
if (this.persistent) {
this.db.prepare(`INSERT OR REPLACE INTO ${this.name} (key, value) VALUES (?, ?);`).run(key, JSON.stringify(this.serializer(data, key)));
if (this.polling) {
this.db.prepare(`INSERT INTO 'internal::changes::${this.name}' (type, key, value, timestamp, pid) VALUES (?, ?, ?, ?, ?);`)
.run('insert', key, JSON.stringify(this.serializer(data, key)), Date.now(), process.pid);
}
}
return super.set(key, this[_clone](data));
}
/**
* Update an existing object value in Enmap by merging new keys. **This only works on objects**, any other value will throw an error.
* Heavily inspired by setState from React's class components.
* This is very useful if you have many different values to update and don't want to have more than one .set(key, value, prop) lines.
* @param {string} key The key of the object to update.
* @param {*} valueOrFunction Either an object to merge with the existing value, or a function that provides the existing object
* and expects a new object as a return value. In the case of a straight value, the merge is recursive and will add any missing level.
* If using a function, it is your responsibility to merge the objects together correctly.
* @example
* // Define an object we're going to update
* enmap.set("obj", { a: 1, b: 2, c: 3 });
*
* // Direct merge
* enmap.update("obj", { d: 4, e: 5 });
* // obj is now { a: 1, b: 2, c: 3, d: 4, e: 5 }
*
* // Functional update
* enmap.update("obj", (previous) => ({
* ...obj,
* f: 6,
* g: 7
* }));
* // this example takes heavy advantage of the spread operators.
* // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
*/
update(key, valueOrFunction) {
this[_readyCheck]();
if (isNil(key)) {
throw new Err('Key not provided for update function', 'EnmapKeyError');
}
this[_check](key, ['Object']);
this[_fetchCheck](key);
const previousValue = this.get(key);
const fn = isFunction(valueOrFunction) ? valueOrFunction : () => merge(previousValue, valueOrFunction);
const merged = fn(previousValue);
this.set(key, merged);
return merged;
}
/**
* Retrieves a key from the enmap. If fetchAll is false, returns a promise.
* @param {string} key The key to retrieve from the enmap.
* @param {string} path Optional. The property to retrieve from the object or array.
* Can be a path with dot notation, such as "prop1.subprop2.subprop3"
* @example
* const myKeyValue = enmap.get("myKey");
* console.log(myKeyValue);
*
* const someSubValue = enmap.get("anObjectKey", "someprop.someOtherSubProp");
* @return {*} The value for this key.
*/
get(key, path = null) {
this[_readyCheck]();
if (isNil(key)) return null;
this[_fetchCheck](key);
key = key.toString();
if(this.autoEnsure !== this.off && !this.has(key)) {
this.set(key, cloneDeep(this.autoEnsure));
}
const data = super.get(key);
if (!isNil(path)) {
this[_check](key, ['Object', 'Array']);
return _get(data, path);
}
return this[_clone](data);
}
/**
* Returns an observable object. Modifying this object or any of its properties/indexes/children
* will automatically save those changes into enmap. This only works on
* objects and arrays, not "basic" values like strings or integers.
* @param {*} key The key to retrieve from the enmap.
* @param {string} path Optional. The property to retrieve from the object or array.
* @return {*} The value for this key.
*/
observe(key, path = null) {
this[_check](key, ['Object', 'Array'], path);
const data = this.get(key, path);
const proxy = onChange(data, () => {
this.set(key, proxy, path);
});
return proxy;
}
/**
* Retrieves the number of rows in the database for this enmap, even if they aren't fetched.
* @return {integer} The number of rows in the database.
*/
get count() {
const data = this.db.prepare(`SELECT count(*) FROM '${this.name}';`).get();
return data['count(*)'];
}
/**
* Retrieves all the indexes (keys) in the database for this enmap, even if they aren't fetched.
* @return {array<string>} Array of all indexes (keys) in the enmap, cached or not.
*/
get indexes() {
const rows = this.db.prepare(`SELECT key FROM '${this.name}';`).all();
return rows.map(row => row.key);
}
/**
* Fetches every key from the persistent enmap and loads them into the current enmap value.
* @return {Enmap} The enmap containing all values.
*/
fetchEverything() {
this[_readyCheck]();
const rows = this.db.prepare(`SELECT * FROM ${this.name};`).all();
for (const row of rows) {
const val = this[_parseData](row.value, row.key);
super.set(row.key, val);
}
return this;
}
/**
* Force fetch one or more key values from the enmap. If the database has changed, that new value is used.
* @param {string|number|Array<string|number>} keyOrKeys A single key or array of keys to force fetch from the enmap database.
* @return {Enmap|*} The Enmap, including the new fetched values, or the value in case the function argument is a single key.
*/
fetch(keyOrKeys) {
this[_readyCheck]();
if (isArray(keyOrKeys)) {
const data = this.db.prepare(`SELECT * FROM ${this.name} WHERE key IN (${'?, '.repeat(keyOrKeys.length).slice(0, -2)})`).all(keyOrKeys);
for (const row of data) {
super.set(row.key, this[_parseData](row.value, row.key));
}
return this;
} else {
const data = this.db.prepare(`SELECT * FROM ${this.name} WHERE key = ?;`).get(keyOrKeys);
if (!data) return null;
super.set(keyOrKeys, this[_parseData](data.value, keyOrKeys));
return this[_parseData](data.value, keyOrKeys);
}
}
/**
* Removes a key or keys from the cache - useful when disabling autoFetch.
* @param {string|number|Array<string|number>} keyOrArrayOfKeys A single key or array of keys to remove from the cache.
* @returns {Enmap} The enmap minus the evicted keys.
*/
evict(keyOrArrayOfKeys) {
if (isArray(keyOrArrayOfKeys)) {
keyOrArrayOfKeys.forEach(key => super.delete(key));
} else {
super.delete(keyOrArrayOfKeys);
}
return this;
}
/**
* Generates an automatic numerical key for inserting a new value.
* This is a "weak" method, it ensures the value isn't duplicated, but does not
* guarantee it's sequential (if a value is deleted, another can take its place).
* Useful for logging, but not much else.
* @example
* enmap.set(enmap.autonum, "This is a new value");
* @return {number} The generated key number.
*/
get autonum() {
let { lastnum } = this.db.prepare("SELECT lastnum FROM 'internal::autonum' WHERE enmap = ?").get(this.name);
lastnum++;
this.db.prepare("INSERT OR REPLACE INTO 'internal::autonum' (enmap, lastnum) VALUES (?, ?)").run(this.name, lastnum);
return lastnum.toString();
}
/**
* Function called whenever data changes within Enmap after the initial load.
* Can be used to detect if another part of your code changed a value in enmap and react on it.
* @example
* enmap.changed((keyName, oldValue, newValue) => {
* console.log(`Value of ${keyName} has changed from: \n${oldValue}\nto\n${newValue}`);
* });
* @param {Function} cb A callback function that will be called whenever data changes in the enmap.
*/
changed(cb) {
this.changedCB = cb;
}
/**
* Shuts down the database. WARNING: USING THIS MAKES THE ENMAP UNUSEABLE. You should
* only use this method if you are closing your entire application.
* Note that honestly I've never had to use this, shutting down the app without a close() is fine.
* @return {Promise<*>} The promise of the database closing operation.
*/
close() {
this[_readyCheck]();
return this.database.close();
}
/**
* Push to an array value in Enmap.
* @param {string} key Required. The key of the array element to push to in Enmap.
* This value MUST be a string or number.
* @param {*} val Required. The value to push to the array.
* @param {string} path Optional. The path to the property to modify inside the value object or array.
* Can be a path with dot notation, such as "prop1.subprop2.subprop3"
* @param {boolean} allowDupes Optional. Allow duplicate values in the array (default: false).
* @example
* // Assuming
* enmap.set("simpleArray", [1, 2, 3, 4]);
* enmap.set("arrayInObject", {sub: [1, 2, 3, 4]});
*
* enmap.push("simpleArray", 5); // adds 5 at the end of the array
* enmap.push("arrayInObject", "five", "sub"); // adds "five" at the end of the sub array
* @returns {Enmap} The enmap.
*/
push(key, val, path = null, allowDupes = false) {
const data = this.get(key);
this[_check](key, 'Array', path);
if (!isNil(path)) {
const propValue = _get(data, path);
if (!allowDupes && propValue.indexOf(val) > -1) return this;
propValue.push(val);
_set(data, path, propValue);
} else {
if (!allowDupes && data.indexOf(val) > -1) return this;
data.push(val);
}
return this.set(key, data);
}
// AWESOME MATHEMATICAL METHODS
/**
* Executes a mathematical operation on a value and saves it in the enmap.
* @param {string} key The enmap key on which to execute the math operation.
* @param {string} operation Which mathematical operation to execute. Supports most
* math ops: =, -, *, /, %, ^, and english spelling of those operations.
* @param {number} operand The right operand of the operation.
* @param {string} path Optional. The property path to execute the operation on, if the value is an object or array.
* @example
* // Assuming
* points.set("number", 42);
* points.set("numberInObject", {sub: { anInt: 5 }});
*
* points.math("number", "/", 2); // 21
* points.math("number", "add", 5); // 26
* points.math("number", "modulo", 3); // 2
* points.math("numberInObject", "+", 10, "sub.anInt");
*
* @returns {Enmap} The enmap.
*/
math(key, operation, operand, path = null) {
this[_check](key, 'Number', path);
const data = this.get(key, path);
if (operation === 'random' || operation === 'rand') {
return this.set(key, Math.round(Math.random() * data), path);
} else {
return this.set(key, this[_mathop](data, operation, operand), path);
}
}
/**
* Increments a key's value or property by 1. Value must be a number, or a path to a number.
* @param {string} key The enmap key where the value to increment is stored.
* @param {string} path Optional. The property path to increment, if the value is an object or array.
* @example
* // Assuming
* points.set("number", 42);
* points.set("numberInObject", {sub: { anInt: 5 }});
*
* points.inc("number"); // 43
* points.inc("numberInObject", "sub.anInt"); // {sub: { anInt: 6 }}
* @returns {Enmap} The enmap.
*/
inc(key, path = null) {
this[_check](key, 'Number', path);
if (isNil(path)) {
let val = this.get(key);
return this.set(key, ++val);
} else {
const data = this.get(key);
let propValue = _get(data, path);
_set(data, path, ++propValue);
return this.set(key, data);
}
}
/**
* Decrements a key's value or property by 1. Value must be a number, or a path to a number.
* @param {string} key The enmap key where the value to decrement is stored.
* @param {string} path Optional. The property path to decrement, if the value is an object or array.
* @example
* // Assuming
* points.set("number", 42);
* points.set("numberInObject", {sub: { anInt: 5 }});
*
* points.dec("number"); // 41
* points.dec("numberInObject", "sub.anInt"); // {sub: { anInt: 4 }}
* @returns {Enmap} The enmap.
*/
dec(key, path = null) {
this[_check](key, 'Number', path);
if (isNil(path)) {
let val = this.get(key);
return this.set(key, --val);
} else {
const data = this.get(key);
let propValue = _get(data, path);
_set(data, path, --propValue);
return this.set(key, data);
}
}
/**
* Returns the key's value, or the default given, ensuring that the data is there.
* This is a shortcut to "if enmap doesn't have key, set it, then get it" which is a very common pattern.
* @param {string} key Required. The key you want to make sure exists.
* @param {*} defaultValue Required. The value you want to save in the database and return as default.
* @param {string} path Optional. If presents, ensures both the key exists as an object, and the full path exists.
* Can be a path with dot notation, such as "prop1.subprop2.subprop3"
* @example
* // Simply ensure the data exists (for using property methods):
* enmap.ensure("mykey", {some: "value", here: "as an example"});
* enmap.has("mykey"); // always returns true
* enmap.get("mykey", "here") // returns "as an example";
*
* // Get the default value back in a variable:
* const settings = mySettings.ensure("1234567890", defaultSettings);
* console.log(settings) // enmap's value for "1234567890" if it exists, otherwise the defaultSettings value.
* @return {*} The value from the database for the key, or the default value provided for a new key.
*/
ensure(key, defaultValue, path = null) {
this[_readyCheck]();
this[_fetchCheck](key);
if (isNil(defaultValue)) throw new Err(`No default value provided on ensure method for "${key}" in "${this.name}"`, 'EnmapArgumentError');
const clonedValue = this[_clone](defaultValue);
if (!isNil(path)) {
if (this.ensureProps) this.ensure(key, {});
if (!this.has(key)) throw new Err(`Key "${key}" does not exist in "${this.name}" to ensure a property`, 'EnmapKeyError');
if (this.has(key, path)) return this.get(key, path);
this.set(key, defaultValue, path);
return defaultValue;
}
if (this.ensureProps && isObject(this.get(key))) {
if (!isObject(clonedValue)) throw new Err(`Default value for "${key}" in enmap "${this.name}" must be an object when merging with an object value.`, 'EnmapArgumentError');
const merged = merge(clonedValue, this.get(key));
this.set(key, merged);
return merged;
}
if (this.has(key)) return this.get(key);
this.set(key, clonedValue);
return clonedValue;
}
/* BOOLEAN METHODS THAT CHECKS FOR THINGS IN ENMAP */
/**
* Returns whether or not the key exists in the Enmap.
* @param {string} key Required. The key of the element to add to The Enmap or array.
* This value MUST be a string or number.
* @param {string} path Optional. The property to verify inside the value object or array.
* Can be a path with dot notation, such as "prop1.subprop2.subprop3"
* @example
* if(enmap.has("myKey")) {
* // key is there
* }
*
* if(!enmap.has("myOtherKey", "oneProp.otherProp.SubProp")) return false;
* @returns {boolean}
*/
has(key, path = null) {
this[_readyCheck]();
this[_fetchCheck](key);
if (!isNil(path)) {
this[_check](key, 'Object');
const data = this.get(key);
return _has(data, path);
}
return super.has(key);
}
/**
* Performs Array.includes() on a certain enmap value. Works similar to
* [Array.includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes).
* @param {string} key Required. The key of the array to check the value of.
* @param {string|number} val Required. The value to check whether it's in the array.
* @param {*} path Required. The property to access the array inside the value object or array.
* Can be a path with dot notation, such as "prop1.subprop2.subprop3"
* @return {boolean} Whether the array contains the value.
*/
includes(key, val, path = null) {
this[_readyCheck]();
this[_fetchCheck](key);
this[_check](key, ['Array', 'Object']);
const data = this.get(key);
if (!isNil(path)) {
const propValue = _get(data, path);
if (isArray(propValue)) {
return propValue.includes(val);
}
throw new Err(`The property "${path}" in key "${key}" is not an Array in the enmap "${this.name}" (property was of type "${propValue && propValue.constructor.name}")`, 'EnmapTypeError');
} else if (isArray(data)) {
return data.includes(val);
}
throw new Err(`The value of key "${key}" is not an Array in the enmap "${this.name}" (value was of type "${data && data.constructor.name}")`, 'EnmapTypeError');
}
/**
* Deletes a key in the Enmap.
* @param {string} key Required. The key of the element to delete from The Enmap.
* @param {string} path Optional. The name of the property to remove from the object.
* Can be a path with dot notation, such as "prop1.subprop2.subprop3"
* @returns {Enmap} The enmap.
*/
delete(key, path = null) {
this[_readyCheck]();
this[_fetchCheck](key);
const oldValue = this.get(key);
if (!isNil(path)) {
let data = this.get(key);
path = toPath(path);
const last = path.pop();
const propValue = path.length ? _get(data, path) : data;
if (isArray(propValue)) {
propValue.splice(last, 1);
} else {
delete propValue[last];
}
if (path.length) {
_set(data, path, propValue);
} else {
data = propValue;
}
this.set(key, data);
} else {
super.delete(key);
if (this.persistent) {
if (this.polling) {
this.db.prepare(`INSERT INTO 'internal::changes::${this.name}' (type, key, timestamp, pid) VALUES (?, ?, ?, ?);`).run('delete', key.toString(), Date.now(), process.pid);
}
this.db.prepare(`DELETE FROM ${this.name} WHERE key = ?`).run(key);
return this;
}
if (typeof this.changedCB === 'function') {
this.changedCB(key, oldValue, null);
}
}
return this;
}
/**
* Deletes everything from the enmap. If persistent, clears the database of all its data for this table.
*/
deleteAll() {
this[_readyCheck]();
if (this.persistent) {
this.db.prepare(`DELETE FROM ${this.name};`).run();
if (this.polling) {
this.db.prepare(`INSERT INTO 'internal::changes::${this.name}' (type, timestamp, pid) VALUES (?, ?, ?);`).run('clear', Date.now(), process.pid);
}
}
super.clear();
}
/**
* Deletes everything from the enmap. If persistent, clears the database of all its data for this table.
* @returns {null}
*/
clear() { return this.deleteAll(); }
/**
* Completely destroys the entire enmap. This deletes the database tables entirely.
* It will not affect other enmap data in the same database, however.
* THIS ACTION WILL DESTROY YOUR DATA AND CANNOT BE UNDONE.
* @returns {null}
*/
destroy() {
this.deleteAll();
this.isDestroyed = true;
const transaction = this.db.transaction((run) => {
for (const stmt of run) {
this.db.prepare(stmt).run();
}
});
transaction([
`DROP TABLE IF EXISTS ${this.name};`,
`DROP TABLE IF EXISTS 'internal::changes::${this.name}';`,
`DELETE FROM 'internal::autonum' WHERE enmap = '${this.name}';`
]);
return null;
}
/**
* Remove a value in an Array or Object element in Enmap. Note that this only works for
* values, not keys. Note that only one value is removed, no more. Arrays of objects must use a function to remove,
* as full object matching is not supported.
* @param {string} key Required. The key of the element to remove from in Enmap.
* This value MUST be a string or number.
* @param {*|Function} val Required. The value to remove from the array or object. OR a function to match an object.
* If using a function, the function provides the object value and must return a boolean that's true for the object you want to remove.
* @param {string} path Optional. The name of the array property to remove from.
* Can be a path with dot notation, such as "prop1.subprop2.subprop3".
* If not presents, removes directly from the value.
* @example
* // Assuming
* enmap.set('array', [1, 2, 3])
* enmap.set('objectarray', [{ a: 1, b: 2, c: 3 }, { d: 4, e: 5, f: 6 }])
*
* enmap.remove('array', 1); // value is now [2, 3]
* enmap.remove('objectarray', (value) => value.e === 5); // value is now [{ a: 1, b: 2, c: 3 }]
* @returns {Enmap} The enmap.
*/
remove(key, val, path = null) {
this[_readyCheck]();
this[_fetchCheck](key);
this[_check](key, ['Array', 'Object']);
const data = this.get(key, path);
const criteria = isFunction(val) ? val : value => val === value;
const index = data.findIndex(criteria);
if (index > -1) {
data.splice(index, 1);
}
return this.set(key, data, path);
}
/**
* Exports the enmap data to a JSON file.
* **__WARNING__**: Does not work on memory enmaps containing complex data!
* @returns {string} The enmap data in a stringified JSON format.
*/
export() {
this[_readyCheck]();
if (this.persistent) this.fetchEverything();
return JSON.stringify({
name: this.name,
version: pkgdata.version,
exportDate: Date.now(),
keys: this.map((value, key) => ({ key, value }))
}, null, 2);
}
/**
* Import an existing json export from enmap from a string. This data must have been exported from enmap,
* and must be from a version that's equivalent or lower than where you're importing it.
* @param {string} data The data to import to Enmap. Must contain all the required fields provided by export()
* @param {boolean} overwrite Defaults to `true`. Whether to overwrite existing key/value data with incoming imported data
* @param {boolean} clear Defaults to `false`. Whether to clear the enmap of all data before importing
* (**__WARNING__**: Any exiting data will be lost! This cannot be undone.)
* @returns {Enmap} The enmap with the new data.
*/
import(data, overwrite = true, clear = false) {
this[_readyCheck]();
if (clear) this.deleteAll();
if (isNil(data)) throw new Err(`No data provided for import() in "${this.name}"`, 'EnmapImportError');
try {
const parsed = JSON.parse(data);
for (const thisEntry of parsed.keys) {
const { key, value } = thisEntry;
if (!overwrite && this.has(key)) continue;
this.set(key, value);
}
} catch (err) {
throw new Err(`Data provided for import() in "${this.name}" is invalid JSON. Stacktrace:\n${err}`, 'EnmapImportError');
}
return this;
}
/**
* Initialize multiple Enmaps easily.
* @param {Array<string>} names Array of strings. Each array entry will create a separate enmap with that name.
* @param {Object} options Options object to pass to each enmap, excluding the name..
* @example
* // Using local variables.
* const Enmap = require('enmap');
* const { settings, tags, blacklist } = Enmap.multi(['settings', 'tags', 'blacklist']);
*
* // Attaching to an existing object (for instance some API's client)
* const Enmap = require("enmap");
* Object.assign(client, Enmap.multi(["settings", "tags", "blacklist"]));
*
* @returns {Array<Map>} An array of initialized Enmaps.
*/
static multi(names, options = {}) {
if (!names.length || names.length < 1) {
throw new Err('"names" argument must be an array of string names.', 'EnmapTypeError');
}
const returnvalue = {};
for (const name of names) {
const enmap = new Enmap({ name, ...options });
returnvalue[name] = enmap;
}
return returnvalue;
}
/* INTERNAL (Private) METHODS */
/*
* Internal Method. Initializes the enmap depending on given values.
* @param {Map} database In order to set data to the Enmap, one must be provided.
* @returns {Promise} Returns the defer promise to await the ready state.
*/
async [_init](database) {
Object.defineProperty(this, 'db', {
value: database,
writable: false,
enumerable: false,
configurable: false
});
if (this.db) {
Object.defineProperty(this, 'isReady', {
value: true,
writable: false,
enumerable: false,
configurable: false
});
} else {
throw new Err('Database Could Not Be Opened', 'EnmapDBConnectionError');
}
const table = this.db.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = ?;").get(this.name);
if (!table['count(*)']) {
this.db.prepare(`CREATE TABLE ${this.name} (key text PRIMARY KEY, value text)`).run();
this.db.pragma('synchronous = 1');
if (this.wal) this.db.pragma('journal_mode = wal');
}
this.db.prepare(`CREATE TABLE IF NOT EXISTS 'internal::changes::${this.name}' (type TEXT, key TEXT, value TEXT, timestamp INTEGER, pid INTEGER);`).run();
this.db.prepare(`CREATE TABLE IF NOT EXISTS 'internal::autonum' (enmap TEXT PRIMARY KEY, lastnum INTEGER)`).run();
if (this.fetchAll) {
await this.fetchEverything();
}
// TEMPORARY MIGRATE CODE FOR AUTONUM
if (this.has('internal::autonum')) {
this.db.prepare("INSERT OR REPLACE INTO 'internal::autonum' (enmap, lastnum) VALUES (?, ?)").run(this.name, this.get('internal::autonum'));
this.delete('internal::autonum');
} else {
const row = this.db.prepare("SELECT lastnum FROM 'internal::autonum' WHERE enmap = ?").get(this.name);
if (!row) {
this.db.prepare("INSERT INTO 'internal::autonum' (enmap, lastnum) VALUES (?, ?)").run(this.name, 0);
}
}
if (this.polling) {
Object.defineProperty(this, 'lastSync', {
value: new Date(),
writable: true,
enumerable: false,
configurable: false
});
setInterval(() => {
const changes = this.db.prepare(`SELECT type, key, value FROM 'internal::changes::${this.name}' WHERE timestamp >= ? AND pid <> ? ORDER BY timestamp ASC;`)
.all(this.lastSync.getTime(), process.pid);
for (const row of changes) {
switch (row.type) {
case 'insert':
super.set(row.key, this[_parseData](row.value, row.key));
break;
case 'delete':
super.delete(row.key);
break;
case 'clear':
super.clear();
break;
}
}
this.lastSync = new Date();
this.db.prepare(`DELETE FROM 'internal::changes::${this.name}' WHERE ROWID IN (SELECT ROWID FROM 'internal::changes::${this.name}' ORDER BY ROWID DESC LIMIT -1 OFFSET 100);`).run();
}, this.pollingInterval);
}
this.ready();
return this.defer;
}
/*
* INTERNAL method to verify the type of a key or property
* Will THROW AN ERROR on wrong type, to simplify code.
* @param {string} key Required. The key of the element to check
* @param {string} type Required. The javascript constructor to check
* @param {string} path Optional. The dotProp path to the property in the object enmap.
*/
[_check](key, type, path = null) {
key = key.toString();
if (!this.has(key)) throw new Err(`The key "${key}" does not exist in the enmap "${this.name}"`, 'EnmapPathError');
if (!type) return;
if (!isArray(type)) type = [type];
if (!isNil(path)) {
this[_check](key, 'Object');
const data = this.get(key);
if (isNil(_get(data, path))) {
throw new Err(`The property "${path}" in key "${key}" does not exist. Please set() it or ensure() it."`, 'EnmapPathError');
}
if (!type.includes(_get(data, path).constructor.name)) {
throw new Err(`The property "${path}" in key "${key}" is not of type "${type.join('" or "')}" in the enmap "${this.name}"
(key was of type "${_get(data, path).constructor.name}")`, 'EnmapTypeError');
}
} else if (!type.includes(this.get(key).constructor.name)) {
throw new Err(`The value for key "${key}" is not of type "${type.join('" or "')}" in the enmap "${this.name}" (value was of type "${this.get(key).constructor.name}")`, 'EnmapTypeError');
}
}
/*
* INTERNAL method to execute a mathematical operation. Cuz... javascript.
* And I didn't want to import mathjs!
* @param {number} base the lefthand operand.
* @param {string} op the operation.
* @param {number} opand the righthand operand.
* @return {number} the result.
*/
[_mathop](base, op, opand) {
if (base == undefined || op == undefined || opand == undefined) throw new Err('Math Operation requires base and operation', 'EnmapTypeError');
switch (op) {
case 'add' :
case 'addition' :
case '+' :
return base + opand;
case 'sub' :
case 'subtract' :
case '-' :
return base - opand;
case 'mult' :
case 'multiply' :
case '*' :
return base * opand;
case 'div' :
case 'divide' :
case '/' :
return base / opand;
case 'exp' :
case 'exponent' :
case '^' :
return Math.pow(base, opand);
case 'mod' :
case 'modulo' :
case '%' :
return base % opand;
}
return null;
}
/**
* Internal method used to validate persistent enmap names (valid Windows filenames)
* @private
*/
[_validateName]() {
this.name = this.name.replace(/[^a-z0-9]/gi, '_').toLowerCase();
}
/*
* Internal Method. Verifies if a key needs to be fetched from the database.
* If persistent enmap and autoFetch is on, retrieves the key.
* @param {string} key The key to check or fetch.
*/
[_fetchCheck](key, force = false) {
key = key.toString();
if (!['String', 'Number'].includes(key.constructor.name)) return;
if (force) {
this.fetch(key);
return;
}
if (super.has(key)) return;
if (!this.persistent || !this.autoFetch) return;
this.fetch(key);
}
/*
* Internal Method. Parses JSON data.
* Reserved for future use (logical checking)
* @param {*} data The data to check/parse
* @returns {*} An object or the original data.
*/
[_parseData](data, key) {
return this.deserializer(JSON.parse(data), key);
}
/*
* Internal Method. Clones a value or object with the enmap's set clone level.
* @param {*} data The data to clone.
* @return {*} The cloned value.
*/
[_clone](data) {
if (this.cloneLevel === 'none') return data;
if (this.cloneLevel === 'shallow') return clone(data);
if (this.cloneLevel === 'deep') return cloneDeep(data);
throw new Err('Invalid cloneLevel. What did you *do*, this shouldn\'t happen!', 'EnmapOptionsError');
}