Skip to content

Commit

Permalink
fix: Do not merge arrays or custom class instances
Browse files Browse the repository at this point in the history
  • Loading branch information
marcbachmann committed Jul 11, 2023
1 parent 436c601 commit 0f32689
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
21 changes: 16 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,17 @@ module.exports = class Conf {
}

merge (obj) {
return _.merge(this.config, obj)
return _.mergeWith(this.config, obj, (configValue, overrideValue) => {
// Do not apply merge on non-plain objects
if (typeof overrideValue === 'object' && overrideValue.constructor !== Object) {
return overrideValue
}

// Do not apply merge on arrays
if (Array.isArray(overrideValue)) {
return overrideValue
}
})
}

toString () {
Expand All @@ -61,11 +71,12 @@ function loadFile (parts, opts) {
}

function getEnvVariables () {
return _.reduce(process.env, function (obj, val, key) {
const env = {}
for (const key of Object.keys(process.env)) {
const k = key.split('__').join('/')
pointer.set(obj, strToPointer(k), val)
return obj
}, {})
pointer.set(env, strToPointer(k), process.env[key])
}
return env
}

function strToPointer (str) {
Expand Down
21 changes: 21 additions & 0 deletions test/unit/conf_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,27 @@ describe('The Conf', () => {
expect(config.get('added')).to.be.true
})

it('does not merge arrays', function () {
const config = new Conf({foo: ['foo', 'bar']})

config.merge({foo: ['quz']})
expect(config.get('foo')).to.deep.equal(['quz'])
})

it('does not merge class instances, keeps the original object', function () {
class Foo {
constructor () {
this.foo = 'foo'
}
}

const config = new Conf({foo: {bar: 'bar'}})

const foo = new Foo()
config.merge({foo})
expect(config.get('foo')).to.equal(foo)
expect(foo.bar).to.equal(undefined)
})
})

describe('set:', () => {
Expand Down

0 comments on commit 0f32689

Please sign in to comment.