Skip to content

Commit

Permalink
fix: throw non-empty object $default error if passing in a date or ot…
Browse files Browse the repository at this point in the history
…her non-POJO
  • Loading branch information
vkarpov15 committed Feb 27, 2020
1 parent 52fc142 commit 76e7bfa
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ function handleDefault(obj, ctx, path) {
if (typeof obj === 'object' && obj != null) {
if (Array.isArray(obj) && obj.length === 0) {
return [];
} else if (!Array.isArray(obj) && Object.keys(obj).length === 0) {
} else if (!Array.isArray(obj) &&
Object.keys(obj).length === 0 &&
[void 0, Object].indexOf(obj.constructor) !== -1) {
return {};
}
throw new Error('Default at path `' + path + '` is a non-empty ' +
Expand Down
5 changes: 4 additions & 1 deletion src/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ class Path {
const numKeys = Array.isArray($default) ?
$default.length :
Object.keys($default).length;
if (numKeys > 0) {
const isInvalidType = Array.isArray($default) ?
false :
[void 0, Object].indexOf($default.constructor) === -1;
if (numKeys > 0 || isInvalidType) {
throw new Error('Default is a non-empty object `' +
util.inspect($default) + '`. Please make `$default` a function ' +
'that returns an object instead');
Expand Down
11 changes: 11 additions & 0 deletions test/unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,17 @@ describe('unmarshal()', function() {
assert.strictEqual(casted.otherProp, void 0);
assert.strictEqual(obj.otherProp, void 0);
});

it('throws if $default is a date', function() {
assert.throws(() => {
const Test = new Archetype({
name: {
$type: Date,
$default: new Date()
}
}).compile('Test');
}, /non-empty object/);
});
});

describe('schema modifications', function() {
Expand Down

0 comments on commit 76e7bfa

Please sign in to comment.