Skip to content

Commit

Permalink
Merge pull request #311 from Robert-Frampton/immutableconfig
Browse files Browse the repository at this point in the history
Method calls to Config helpers should return new objects to avoid unintended mutation
  • Loading branch information
jbalsas authored Nov 29, 2017
2 parents 3c088e4 + a1f7cdb commit 82913d7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
12 changes: 6 additions & 6 deletions packages/metal-state/src/Config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict';

import {object} from 'metal';
import validators from './validators';

/**
Expand Down Expand Up @@ -233,11 +232,12 @@ function destructShapeOfConfigs(shape) {
*/
function mergeConfig(context, config) {
let obj = context;
if (obj === Config) {
obj = Object.create(Config);
obj.config = {};
}
object.mixin(obj.config, config);
const objConfig = obj.config || {};

obj = Object.create(Config);
obj.config = {};

Object.assign(obj.config, objConfig, config);
return obj;
}

Expand Down
22 changes: 22 additions & 0 deletions packages/metal-state/test/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -284,4 +284,26 @@ describe('Config', function() {
assert.ok(config.config.validator(10));
assert.ok(config.config.validator('test') instanceof Error);
});

it('should not mutate config object with subsequent method calls', function() {
const config = Config.string();
const config2 = config.oneOf(['1', '2']);
const config3 = config2.required();

assert.notDeepEqual(config, config2);
assert.notDeepEqual(config, config3);
assert.notDeepEqual(config2, config3);

assert.ok(config.config.validator(1) instanceof Error);
assert.ok(config2.config.validator(1) instanceof Error);
assert.ok(config3.config.validator(1) instanceof Error);

assert.ok(config.config.validator('1'));
assert.ok(config2.config.validator('1'));
assert.ok(config3.config.validator('3') instanceof Error);

assert.isTrue(config3.config.required);
assert.isUndefined(config.config.required);
assert.isUndefined(config2.config.required);
});
});

0 comments on commit 82913d7

Please sign in to comment.