Skip to content

Commit

Permalink
feat(unmarshal): report errors from $transform
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Sep 14, 2017
1 parent 2d11cf5 commit a8c9e3d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/unmarshal/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,12 @@ function visitArray(arr, schema, projection, path) {
arr.forEach(function(value, index) {
const pathOptions = schema._paths[newPath];
if (pathOptions.$transform != null) {
arr[index] = pathOptions.$transform(arr[index]);
try {
arr[index] = pathOptions.$transform(arr[index]);
} catch (err) {
error.markError(`newPath.${index}`, err);
return;
}
value = arr[index];
}
if (pathOptions.$type === Array ||
Expand Down Expand Up @@ -171,7 +176,12 @@ function visitObject(obj, schema, projection, path) {
const newSchema = schema._paths[newPath];
const pathOptions = schema._paths[newPath];
if (pathOptions.$transform != null) {
obj[key] = pathOptions.$transform(obj[key]);
try {
obj[key] = pathOptions.$transform(obj[key]);
} catch (err) {
error.markError(newPath, err);
return;
}
value = obj[key];
}
if (newSchema.$type == null) {
Expand Down
20 changes: 20 additions & 0 deletions test/unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,26 @@ describe('unmarshal()', function() {
});
});

it('$transform errors', function() {
const Test = new Archetype({
str: {
$type: Object,
$transform: JSON.parse
}
}).compile();

let threw = false;
try {
new Test({
str: { already: 'object' }
});
} catch (error) {
assert.ok(error.errors['str']);
threw = true;
}
assert.ok(threw);
});

it('to()', function() {
const n = Archetype.to('2', 'number');
assert.strictEqual(n, 2)
Expand Down

0 comments on commit a8c9e3d

Please sign in to comment.