-
Notifications
You must be signed in to change notification settings - Fork 97
/
index.js
50 lines (43 loc) · 1.67 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
'use strict';
const dotenv = require('dotenv');
const fs = require('fs');
const MissingEnvVarsError = require('./MissingEnvVarsError.js');
function difference (arrA, arrB) {
return arrA.filter(a => arrB.indexOf(a) < 0);
}
function compact (obj) {
const result = {};
Object.keys(obj).forEach(key => {
if (obj[key]) {
result[key] = obj[key];
}
});
return result;
}
module.exports = {
config: function(options = {}) {
const dotenvResult = dotenv.config(options);
const example = options.example || options.sample || '.env.example';
const allowEmptyValues = options.allowEmptyValues || false;
const processEnv = allowEmptyValues ? process.env : compact(process.env);
const exampleVars = dotenv.parse(fs.readFileSync(example));
const missing = difference(Object.keys(exampleVars), Object.keys(processEnv));
if (missing.length > 0) {
throw new MissingEnvVarsError(allowEmptyValues, options.path || '.env', example, missing, dotenvResult.error);
}
// Key/value pairs defined in example file and resolved from environment
const required = Object.keys(exampleVars).reduce((acc, key) => {
acc[key] = process.env[key];
return acc;
}, {});
const error = dotenvResult.error ? { error: dotenvResult.error } : {};
const result = {
parsed: dotenvResult.error ? {} : dotenvResult.parsed,
required: required
};
return Object.assign(result, error);
},
parse: dotenv.parse,
MissingEnvVarsError: MissingEnvVarsError
};
module.exports.MissingEnvVarsError = MissingEnvVarsError;