Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
116 lines (99 loc) · 3.16 KB
/
Copy pathindex.js
File metadata and controls
116 lines (99 loc) · 3.16 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
'use strict';
const async = require( 'async' );
const Delver = require( 'delver' );
const extend = require( 'extend' );
const fs = require( 'fs' );
const path = require( 'path' );
const yaml = require( 'js-yaml' );
const DEFAULTS = {
envPrefix: 'CONFIG',
envHierarchy: true,
allowEmptyEnvVars: false,
files: [
'CONFIG_DEFAULTS.json',
'config.json',
'CONFIG_DEFAULTS.yaml',
'config.yaml',
'CONFIG_DEFAULTS.yml',
'config.yml'
],
order: [
'files',
'env',
'config'
]
};
const loaders = {
files: function( options, config, callback ) {
async.eachSeries( options.files, function( filename, next ) {
const file = path.join( process.cwd(), filename );
fs.access( file, fs.R_OK, function( error ) {
if ( !error ) {
switch ( path.extname( file ).toLowerCase() ) {
case '.yaml':
case '.yml':
extend( config, yaml.safeLoad( fs.readFileSync( file, 'utf8' ) ) );
break;
default:
extend( config, require( file ) );
break;
}
}
next();
} );
}, callback );
},
env: function( options, config, callback ) {
for ( const varName in process.env ) {
if ( !process.env.hasOwnProperty( varName ) ) {
continue;
}
if ( varName.indexOf( options.envPrefix + '_' ) !== 0 ) {
continue;
}
if ( !options.allowEmptyEnvVars && ( typeof process.env[ varName ] === 'undefined' || process.env[ varName ].length === 0 ) ) {
continue;
}
let key = null;
if ( options.envHierarchy ) {
key = varName.split( '_' ).slice( 1 ).join( '.' ).toLowerCase();
}
else {
key = varName.substring( ( options.envPrefix + '_' ).length ).toLowerCase();
}
Delver.set( config, key, process.env[ varName ] );
}
callback();
},
config: function( options, config, callback ) {
extend( config, options.config );
callback();
}
};
module.exports = {
load: function( _options, callback ) {
if ( !callback ) {
callback = _options;
_options = null;
}
const options = extend( {}, DEFAULTS, _options );
let config = {};
async.eachSeries( options.order, function( type, next ) {
const loader = loaders[ type ];
if ( !loader ) {
next( 'Invalid loader type: ' + type );
return;
}
loader( options, config, next );
}, function( error ) {
if ( error ) {
callback( error );
return;
}
if ( options.collapse ) {
config = extend( true, {}, config, config[ options.collapse ] );
}
callback( null, config );
} );
}
};