-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
701 lines (619 loc) · 19.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
let fs = require('fs');
const path = require("path");
const {UnknownFileFormatError, ParseFailureError, NoConfigFoundError} = require("./errors");
/**
* @class
* @classdesc Main class of config-discovery, every usage starts with instantiating this class.
*/
class Config {
#meta;
#constructor_defaults = {parser: JSON.parse, logger: console.log}
/**
* @param [options.parser=JSON.parse] IGNORED, this is legacy, will remove in the future.
* @param [options.logger=console.log] Logger function, function(string)
*/
constructor(options = {parser: JSON.parse, logger: console.log}) {
let _options = _mergeConfigs(this.#constructor_defaults, options);
this.#meta = {config: {}, logger: _options.logger};
}
/**
* Will try to load initial config from provided
* absolutePath. If config file is not found, it does nothing.
*
* @example
*
* // With out-of-the-box support for JSON/YAML
* let config = new Config()
* .fromFile('/config/config.json')
* .get();
*
* // Or with a custom file
* let xmlParser = (...) => .... ;
* let config = new Config()
* .fromFile('/config/config.xml', xmlParser)
* .get();
*
*
* @param {string} absolutePath - Possible location of a configuration file
* @param {Parser} [options.customParser=null] - Custom parser for the config file, must accept fs.readFileSync().toString() and return JSON Object.
* @throws {UnknownFileFormatError} - When passing a non YAML/JSON config without customParser, or when file extension is not known.
* @throws {ParseFailureError} - When native JSON/YAML or customParser fails to parse provided config.
* @returns {FindFirstConfigProvider}
*/
fromFile(absolutePath, options = {customParser: null}) {
const {logger} = this.#meta;
let object = _loadFile(absolutePath, options);
let chainObject = this.fromObject(object);
if (this.#meta.foundFirst) {
_tryLog(`Configuration ${absolutePath} found first, will use as configuration`, logger);
}
return chainObject;
}
/**
* Will try to load initial config from the environment based
* on provided prototype. If prototype is not satisfied it does
* nothing.
*
* @example
*
* // Given example environment variables exist
* // ENV_VARIABLE_URL="dev-db:5432/dev"
* // ENV_VARIABLE_USERNAME="dev"
* // ENV_VARIABLE_PASSWORD="p@sSword123"
*
* let prototype = {
* url: 'ENV_VARIABLE_URL',
* nested: {
* username: 'ENV_VARIABLE_USERNAME',
* password: 'ENV_VARIABLE_PASSWORD'
* }
* };
*
*
* let config = new Config()
* .fromEnv(prototype)
* .get();
*
*
* // Will result in
* // let config = {
* // url: 'dev-db:5432/dev',
* // nested: {
* // username: 'dev',
* // password: 'p@sSword123'
* // }
* // };
*
* @param {JSON} prototype Prototype for an object to generate from the ENV
* @returns {FindFirstConfigProvider}
*/
fromEnv(prototype) {
const {logger} = this.#meta;
let object = {};
if (_isDefinedNonNull(prototype) && _isNotEmpty(prototype)) {
object = _pullEnvironmentPrototype(prototype);
}
let chainObject = this.fromObject(object);
if (this.#meta.foundFirst) {
_tryLog(`Environment configuration with prototype ${JSON.stringify(prototype)} found first, will use as configuration`, logger);
}
return chainObject;
}
/**
* Will try to load initial config from provided object,
* if jsonObject is empty or not valid, will ignore.
*
* Intended for quick debugging or setup for a follow up patching.
*
* Though I understand that it may not be necessary in this context.
* @example
*
* let debugConfig = {
* username: 'user',
* password: 'password'
* };
*
*
* let config = new Config()
* .fromObject(debugConfig)
* .get();
*
*
* @param {JSON} jsonObject A possibly non empty object
* @returns {FindFirstConfigProvider}
*/
fromObject(jsonObject) {
const {config, logger} = this.#meta;
if (_isDefinedNonNull(jsonObject) && _isNotEmpty(jsonObject)) {
_mergeConfigs(config, jsonObject);
this.#meta.foundFirst = true;
_tryLog(`Config object loaded.`, logger);
}
return new FindFirstConfigProvider(this.#meta);
}
}
/**
* @class
* UTILITY CLASS DO NOT INSTANTIATE.
*/
class FindFirstConfigProvider {
#meta
/**
* @private
*/
constructor(meta) {
this.#meta = meta;
}
/**
* @deprecated
* Replaced with orFile(absolutePath) for interface consistency.
*
* @param {string} absolutePath - Possible location of a configuration file
* @param {Parser} [options.customParser=null] - Custom parser for the config file, must accept fs.readFileSync().toString() and return JSON Object.
* @throws {UnknownFileFormatError} - When passing a non YAML/JSON config without customParser, or when file extension is not known.
* @throws {ParseFailureError} - When native JSON/YAML or customParser fails to parse provided config.
* @returns {FindFirstConfigProvider}
*/
or(absolutePath, options = {customParser: null}) {
return this.orFile(absolutePath, options);
}
/**
* Will try to load configuration from absolutePath if the previous
* attempts from from*() or another or*() failed.
*
* @example
*
* // With out-of-the-box support for JSON/YAML
* let config = new Config()
* .fromFile('/config/config.json')
* .orFile('/var/config.yaml')
* .orFile('config.yml')
* .get();
*
* // Or with a custom file
* let xmlParser = (string) => JSON ;
* let propParser = (string) => JSON ;
*
* let config = new Config()
* .fromFile('/config/config.yaml')
* .orFile('/var/config.xml', xmlParser)
* .orFile('/etc/configs/config.properties' propParser)
* .get();
*
*
* @param {string} absolutePath - Possible location of a configuration file
* @param {Parser} [options.customParser=null] - Custom parser for the config file, must accept fs.readFileSync().toString() and return JSON Object.
* @throws {UnknownFileFormatError} - When passing a non YAML/JSON config without customParser, or when file extension is not known.
* @throws {ParseFailureError} - When native JSON/YAML or customParser fails to parse provided config.
* @returns {FindFirstConfigProvider}
*/
orFile(absolutePath, options = {customParser: null}) {
const {foundFirst, logger} = this.#meta;
let object = {};
if (!foundFirst) {
object = _loadFile(absolutePath, options);
}
let self = this.orObject(object);
if (this.#meta.foundFirst) {
_tryLog(`Configuration ${absolutePath} found first, will use as configuration`, logger);
}
return self;
}
/**
* Will try to load configuration from environment
* based on provided prototype if the previous
* attempts from from*() or another or*() failed.
*
* @example
*
* // Given example environment variables exist
* // ENV_VARIABLE_URL="dev-db:5432/dev"
* // ENV_VARIABLE_USERNAME="dev"
* // ENV_VARIABLE_PASSWORD="p@sSword123"
*
* let prototype = {
* url: 'ENV_VARIABLE_URL',
* nested: {
* username: 'ENV_VARIABLE_USERNAME',
* password: 'ENV_VARIABLE_PASSWORD'
* }
* };
*
*
* let config = new Config()
* .fromFile('/configs/non-existing-config.yaml')
* .orEnv(prototype)
* .get();
*
* // Will result in this, if the previous config was not found.
* //
* // let config = {
* // url: 'dev-db:5432/dev',
* // nested: {
* // username: 'dev',
* // password: 'p@sSword123'
* // }
* // };
*
* @param prototype Prototype for an object to generate from the ENV
* @returns {FindFirstConfigProvider}
*/
orEnv(prototype) {
const {foundFirst, logger} = this.#meta;
if (!foundFirst) {
if (_isDefinedNonNull(prototype) && _isNotEmpty(prototype)) {
let object = _pullEnvironmentPrototype(prototype);
this.orObject(object);
if (this.#meta.foundFirst) {
_tryLog(`Environment configuration with prototype ${JSON.stringify(prototype)} found first, will use as configuration`, logger);
}
}
}
return this;
}
/**
* Will try to load configuration from provided object if the previous
* attempt from from*() or another or*() failed.
*
* Intended for quick debugging, and in code default configurations
*
* Though I understand that it may not be necessary in this context.
* @example
*
* let debugConfig = {
* dbUrl: 'debugdb:5432/debugdb'
* credentials: {
* username: 'user',
* password: 'password'
* }
* };
*
*
* let config = new Config()
* .fromFile('/configs/production-config.yaml')
* .orObject(debugConfig)
* .get();
*
*
* @param jsonObject A possibly non empty jsonObject
* @returns {FindFirstConfigProvider}
*/
orObject(jsonObject) {
const {config, foundFirst, logger} = this.#meta;
if (!foundFirst) {
if (_isDefinedNonNull(jsonObject) && _isNotEmpty(jsonObject)) {
_mergeConfigs(config, jsonObject);
this.#meta.foundFirst = true;
_tryLog(`Config object loaded.`, logger);
}
}
return this;
}
/**
* Marks the transition from finding first config to
* patching current config from another config file
* or config assembled from the environment.
* @throws NoConfigFoundError When none of the patch alternatives are found, you can't patch a non existing configuration.
* @returns {PatchingConfigProvider}
*/
thenPatchWith() {
if (!this.#meta.foundFirst) {
throw new NoConfigFoundError(`No config found, cannot continue with patching.`);
}
let metadata = this.#meta;
this.#meta = undefined;
return new PatchingConfigProvider(metadata);
}
/**
* Will return the configuration.
* @returns {JSON} The configuration object.
*/
get() {
if (!this.#meta.foundFirst) {
throw new NoConfigFoundError(`No configuration found.`);
}
return this.#meta.config;
}
}
/**
* @class
* UTILITY CLASS DO NOT INSTANTIATE.
*/
class PatchingConfigProvider {
#meta
/**
* @private
*/
constructor(meta) {
this.#meta = meta;
}
/**
* Will try to load specified config file,
* and patch current configuration.
*
* @example
*
* // Given Example
* //
* // patch.yaml --
* // credentials:
* // username: user
* // password: mypassword
* //
* // config.json --
* // {
* // "url": "database:5432/devdb"
* // }
* //
* // patch.properties --
* // credentials.username = user
* // credentials.password = mypassword
* //
*
* // With out-of-the-box support for JSON/YAML
* let config = new Config()
* .fromFile('/config/config.json')
* .thenPatchWith()
* .configFile('/etc/credentials/patch.yaml')
* .get();
*
* // Or with a custom file
* let propParser = (string) => JSON ;
*
* let config = new Config()
* .fromFile('/config/config.yaml')
* .thenPatchWith()
* .orFile('/etc/configs/patch.properties' propParser)
* .get();
*
*
* @param {string} absolutePath - Possible location of a configuration file
* @param {Parser} [options.customParser=null] - Custom parser for the config file, must accept fs.readFileSync().toString() and return JSON Object.
* @throws {UnknownFileFormatError} - When passing a non YAML/JSON config without customParser, or when file extension is not known.
* @throws {ParseFailureError} - When native JSON/YAML or customParser fails to parse provided config.
* @returns {PatchingConfigProvider}
*/
configFile(absolutePath, options = {customParser: null}) {
let {logger} = this.#meta;
let object = _loadFile(absolutePath, options);
let self = this.object(object);
if (_isNotEmpty(object)) {
_tryLog(`Patched with file ${absolutePath}`, logger);
}
return self;
}
/**
* @deprecated
* Replaced with env(prototype) for interface consistency.
*
* @param prototype Prototype of expected object from the environment.
* @returns {PatchingConfigProvider}
*/
patchWithEnv(prototype) {
return this.env(prototype);
}
/**
*
* Will try to patch current config with JSON object generated
* from environment prototype.
*
* @example
*
* // Given example
* // ENV_VARIABLE_USERNAME="dev"
* // ENV_VARIABLE_PASSWORD="p@sSword123"
* //
* // config.yaml --
* // dbUrl: 'dev-db:5432/dev'
* //
* //
*
* let env_credentials = {
* credentials: {
* username: 'ENV_VARIABLE_USERNAME',
* password: 'ENV_VARIABLE_PASSWORD'
* }
* };
*
*
* let config = new Config()
* .fromFile('/configs/config.yaml')
* .thenPatchWith()
* .env(env_credentials)
* .get();
*
*
* // Will result in
* // let config = {
* // dbUrl: 'dev-db:5432/dev',
* // nested: {
* // username: 'dev',
* // password: 'p@sSword123'
* // }
* // };
*
* @param prototype
* @returns {PatchingConfigProvider}
*/
env(prototype) {
let {logger} = this.#meta;
if (_isDefinedNonNull(prototype) && _isNotEmpty(prototype)) {
let envObject = _pullEnvironmentPrototype(prototype);
this.object(envObject);
if (_isNotEmpty(envObject)) {
_tryLog(`Patched with env prototype ${JSON.stringify(prototype)}`, logger);
}
}
return this;
}
/**
*
* Will try to patch current config with JSON object if
* its is defined and not empty.
*
* Intended for quick debugging, and in code default configurations
*
* Though I understand that it may not be necessary in this context.
* @example
*
* let debugPatch = {
* dbUrl: 'debugdb:5432/debugdb'
* credentials: {
* username: 'user',
* password: 'password'
* }
* };
*
*
* let config = new Config()
* .fromFile('/configs/production-config.yaml')
* .thenPatchWith()
* .object(debugConfig)
* .get();
*
* @param jsonObject
* @returns {PatchingConfigProvider}
*/
object(jsonObject) {
if (_isDefinedNonNull(jsonObject) && _isNotEmpty(jsonObject)) {
let {config} = this.#meta;
_mergeConfigs(config, jsonObject);
_tryLog(`Applied config object patch`, this.#meta.logger);
}
return this;
}
/**
* Will return the configuration.
* @returns {JSON} The configuration object.
*/
get() {
// _tryLog(`WARNING: No patches were found and non were applied.`, this.#meta.logger);
return this.#meta.config;
}
}
/**
* @ignore
* */
function _mergeConfigs(target, source) {
Object.keys(source).forEach(key => {
let obj = source[key];
if (typeof obj === 'object') {
if (_isDefinedNonNull(target[key])) {
_mergeConfigs(target[key], obj);
} else {
target[key] = source[key];
}
} else {
target[key] = source[key];
}
});
return target;
}
/**
* @ignore
* */
function _pullEnvironmentPrototype(prototype) {
let result = {};
let prototypeKeys = Object.keys(prototype);
for (let key of prototypeKeys) {
let value = undefined;
if (typeof prototype[key] === 'object') {
value = _pullEnvironmentPrototype(prototype[key]);
} else {
value = process.env[prototype[key]];
}
if (!_isDefinedNonNull(value) || !_isNotEmpty(value)) {
result = {};
break;
}
result[key] = value;
}
return result;
}
/**
* @ignore
*/
function _isNotEmpty(object) {
return Object.keys(object).length > 0;
}
/**
* @ignore
*/
function _isDefinedNonNull(object) {
return (object !== undefined && object !== null);
}
/**
* @ignore
*/
function _getParser(filePath) {
let extension = path.extname(filePath);
if (extension.length === 0) {
throw new UnknownFileFormatError(`Can't find file extensions of ${filePath}, try passing custom parser`);
}
extension = extension.slice(1, extension.length);
let parser = KNOWN_FILE_PARSER[extension];
if (!_isDefinedNonNull(parser)) {
throw new UnknownFileFormatError(`Config-discovery auto parse only supports JSON and YAML/YML files, you can pass your own parser via options:{ customParser: (stringValue) => JSONObject }.`)
}
return parser;
}
/**
* @ignore
* */
function _loadFile(absolutePath, options = {customParser: null}) {
let object = {};
if (fs.existsSync(absolutePath)) {
let byteData = fs.readFileSync(absolutePath);
let parser = _isDefinedNonNull(options.customParser) ? options.customParser : _getParser(absolutePath);
try {
object = parser(byteData.toString());
} catch (e) {
throw new ParseFailureError(e.toString());
}
}
return object;
}
/**
* @ignore
*/
function _tryLog(message, logger) {
let env = process.env['NODE_ENV'];
if (_isDefinedNonNull(logger) && (env !== 'production' && env !== 'test')) {
logger(message);
}
}
/**
* @ignore
*/
const yamlParser = (dataString) => {
return require('yaml').parse(dataString);
}
/**
* @ignore
*/
const jsonParser = (dataString) => {
return JSON.parse(dataString);
}
/**
* @ignore
*/
const KNOWN_FILE_PARSER = {
yaml: yamlParser,
yml: yamlParser,
json: jsonParser
};
module.exports = Config
/**
* Custom parser callback
*
* @callback Parser
* @param {string} rawString - String loaded from fs.readSync().toString().
* @return {JSON} - Parsed JSON object.
*/
/**
* Custom parser callback
*
* @callback Logger
* @param {string} rawString - String loaded from fs.readSync().toString().
* @return {void|any} - Parsed JSON object.
*/