Skip to content

Commit 6bb5561

Browse files
authored
feat: add env prefix option (#428)
* feat: add env prefix option * chore: remove console.log from test
1 parent 831fde3 commit 6bb5561

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

lib/nconf/stores/env.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ var Env = exports.Env = function (options) {
2121
options = options || {};
2222
this.type = 'env';
2323
this.readOnly = options.readOnly !== undefined ? options.readOnly : true;
24+
this.prefix = options.prefix || '';
2425
this.whitelist = options.whitelist || [];
2526
this.lowerCase = options.lowerCase || false;
2627
this.parseValues = options.parseValues || false;
@@ -57,6 +58,15 @@ Env.prototype.loadEnv = function () {
5758

5859
var env = process.env;
5960

61+
if (this.prefix) {
62+
env = {};
63+
Object.keys(process.env).forEach(function (key) {
64+
if (key.indexOf(self.prefix) === 0) {
65+
env[key.replace(self.prefix, '')] = process.env[key];
66+
}
67+
});
68+
}
69+
6070
if (this.lowerCase) {
6171
env = {};
6272
Object.keys(process.env).forEach(function (key) {

test/stores/env.test.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
var nconf = require('../../lib/nconf');
99

1010
process.env.DEEP__NESTED__VALUE = 'foo';
11+
process.env.DEEP2__NESTED__VALUE = 'bar';
1112

1213
describe('nconf/stores/env, An instance of nconf.Env', () => {
1314
it("should have the correct methods defined", () => {
@@ -33,5 +34,17 @@ describe('nconf/stores/env, An instance of nconf.Env', () => {
3334

3435
expect(env.accessSeparator).toBe('.');
3536
expect(env.get('DEEP.NESTED.VALUE')).toBe('foo');
36-
})
37+
});
38+
it("should filter and strip prefix from environment variables", () => {
39+
var env = new nconf.Env({prefix: 'DEEP2__'});
40+
env.loadSync();
41+
expect(env.get('DEEP__NESTED__VALUE')).toBeUndefined();
42+
expect(env.get('NESTED__VALUE')).toBe('bar');
43+
});
44+
it("should filter and strip prefix from environment variables with input and access separator", () => {
45+
var env = new nconf.Env({prefix: 'DEEP2__', accessSeparator: '.', inputSeparator: '__' });
46+
env.loadSync();
47+
expect(env.get('DEEP.NESTED.VALUE')).toBeUndefined();
48+
expect(env.get('NESTED.VALUE')).toBe('bar');
49+
});
3750
});

0 commit comments

Comments
 (0)