Skip to content

Commit

Permalink
Merge pull request #45 from ondrejsevcik/master
Browse files Browse the repository at this point in the history
Add check for env variables presence
  • Loading branch information
jasonmit authored Dec 6, 2017
2 parents 7dbd506 + d0d6b79 commit a3c1b28
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ Next, configure `config/dotenv.js`.
// config/dotenv.js
module.exports = function(env) {
return {
clientAllowedKeys: ['DROPBOX_KEY']
clientAllowedKeys: ['DROPBOX_KEY'],
// Fail build when there is missing any of clientAllowedKeys environment variables.
// By default false.
failOnMissingKey: false,
};
};
```
Expand Down
40 changes: 31 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,45 @@ module.exports = {
let configFactory = path.join(root, 'config', 'dotenv.js');
let options = {
path: path.join(root, '.env'),
clientAllowedKeys: []
clientAllowedKeys: [],
failOnMissingKey: false,
};

if (fs.existsSync(configFactory)) {
Object.assign(options, require(configFactory)(this._resolveEnvironment()));
}

if (fs.existsSync(options.path) && dotenv.config({ path: options.path })) {
let loadedConfig = dotenv.parse(fs.readFileSync(options.path));
let allowedKeys = options.clientAllowedKeys || [];
let loadedConfig = dotenv.config({ path: options.path });

this._config = allowedKeys.reduce((accumulator, key) => {
accumulator[key] = loadedConfig[key];

return accumulator;
}, {});
// It might happen that environment config is missing or corrupted
if (loadedConfig.error) {
let loadingErrMsg = `[ember-cli-dotenv]: ${loadedConfig.error.message}`;
if (options.failOnMissingKey) {
throw new Error(loadingErrMsg);
} else {
console.warn(loadingErrMsg);
return;
}
}

let allowedKeys = options.clientAllowedKeys || [];

allowedKeys.forEach(key => {
if (loadedConfig.parsed[key] === undefined) {
let errMsg = '[ember-cli-dotenv]: Required environment variable \'' + key + '\' is missing.';
if (options.failOnMissingKey) {
throw new Error(errMsg);
} else {
console.warn(errMsg);
}
}
});

this._config = allowedKeys.reduce((accumulator, key) => {
accumulator[key] = loadedConfig.parsed[key];

return accumulator;
}, {});
},

_resolveEnvironment() {
Expand Down

0 comments on commit a3c1b28

Please sign in to comment.