Skip to content
This repository has been archived by the owner on Feb 16, 2021. It is now read-only.

Commit

Permalink
fromJSON makes use of defaultProps while deserializing a struct, fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
rkmax authored and gcanti committed Feb 24, 2018
1 parent fbac99f commit a5367d0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/fromJSON.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,15 @@ function fromJSON(value, type, path) {
});
}
var props = type.meta.props;
var defaultProps = type.meta.defaultProps;
ret = {};
for (k in props) {
var actual = value[k];
if (actual === undefined) {
actual = defaultProps[k];
}
if (props.hasOwnProperty(k)) {
ret[k] = fromJSON(value[k], props[k], ( process.env.NODE_ENV !== 'production' ? path.concat(k + ': ' + getTypeName(props[k])) : null ));
ret[k] = fromJSON(actual, props[k], ( process.env.NODE_ENV !== 'production' ? path.concat(k + ': ' + getTypeName(props[k])) : null ));
}
}
return new type(ret);
Expand Down
25 changes: 25 additions & 0 deletions test/fromJSON.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,31 @@ describe('fromJSON', function () {
}, '[tcomb] Invalid value undefined supplied to MyType/name: String');
});

it('should handle struct with options.defaultProps', function () {
var MyType = t.struct({
surname: t.String,
number: t.Number
}, {
name: 'MyType',
defaultProps: {
surname: 'Canti',
get number() {
return 2;
}
}
});

var source = {};
var expected = {
surname: 'Canti',
number: 2
};
var json = jsonify(source);
var actual = fromJSON(json, MyType);
assert.ok(actual instanceof MyType);
assert.deepEqual(actual, expected);
});

it('should handle interface', function () {
var MyType = t.interface({
name: t.String,
Expand Down

0 comments on commit a5367d0

Please sign in to comment.