Skip to content

Commit 5f0bfdf

Browse files
committed
feat: Push errors on target's symbol property when validation does not pass
1 parent 5c812ea commit 5f0bfdf

File tree

1 file changed

+34
-12
lines changed

1 file changed

+34
-12
lines changed

src/MorphismTree.ts

+34-12
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import {
1313
SCHEMA_OPTIONS_SYMBOL,
1414
isEmptyObject
1515
} from './helpers';
16+
import { parse, ValidationError, ERRORS, targetContainsErrors } from './validation/reporter';
17+
import { PropertyValidationError } from './validation/PropertyValidationError';
1618

1719
export enum NodeKind {
1820
Root = 'Root',
@@ -185,19 +187,39 @@ export class MorphismSchemaTree<Target, Source> {
185187
// Action<Object>: a path and a function: [ destination : { path: 'source', fn:(fieldValue, items) }]
186188
return ({ object, items, objectToCompute }) => {
187189
let result;
188-
try {
189-
let value;
190-
if (Array.isArray(action.path)) {
191-
value = aggregator(action.path, object);
192-
} else if (isString(action.path)) {
193-
value = get(object, action.path);
190+
if (Array.isArray(action.path)) {
191+
result = aggregator(action.path, object);
192+
} else if (isString(action.path)) {
193+
result = get(object, action.path);
194+
}
195+
196+
if (action.fn) {
197+
try {
198+
result = action.fn.call(undefined, result, object, items, objectToCompute);
199+
} catch (e) {
200+
e.message = `Unable to set target property [${targetProperty}].
201+
\n An error occured when applying [${action.fn.name}] on property [${action.path}]
202+
\n Internal error: ${e.message}`;
203+
throw e;
204+
}
205+
}
206+
207+
if (action.type) {
208+
try {
209+
result = parse(result, action.type);
210+
} catch (error) {
211+
if (error instanceof PropertyValidationError) {
212+
const validationError: ValidationError = { type: error.type, value: error.value, targetProperty };
213+
214+
if (targetContainsErrors(objectToCompute)) {
215+
objectToCompute[ERRORS].push(validationError);
216+
} else {
217+
objectToCompute[ERRORS] = [validationError];
218+
}
219+
} else {
220+
throw error;
221+
}
194222
}
195-
result = action.fn.call(undefined, value, object, items, objectToCompute);
196-
} catch (e) {
197-
e.message = `Unable to set target property [${targetProperty}].
198-
\n An error occured when applying [${action.fn.name}] on property [${action.path}]
199-
\n Internal error: ${e.message}`;
200-
throw e;
201223
}
202224
return result;
203225
};

0 commit comments

Comments
 (0)