44 lines
1.2 KiB
JavaScript
44 lines
1.2 KiB
JavaScript
import { Data_Validation_Failed, Data_Coercion_Failed } from '@efforting.tech/errors';
|
|
|
|
export class Field_Configuration {
|
|
constructor(name, validation_function=null, coercion_function=null, expected_description=undefined) {
|
|
Object.assign(this, { name, validation_function, coercion_function, expected_description });
|
|
}
|
|
|
|
check_validation(value) {
|
|
const { validation_function } = this;
|
|
return !validation_function || validation_function(value);
|
|
}
|
|
|
|
validate(value, target=undefined) {
|
|
const { validation_function, name, expected_description } = this;
|
|
if (!this.check_validation(value)) {
|
|
throw new Data_Validation_Failed({
|
|
name, validation_function, value,
|
|
target, expected_description,
|
|
});
|
|
}
|
|
}
|
|
|
|
coerce(value, target=undefined) {
|
|
const { coercion_function, name, expected_description } = this;
|
|
try {
|
|
return coercion_function ? coercion_function(value) : value;
|
|
} catch (e) {
|
|
throw new Data_Coercion_Failed({
|
|
name, coercion_function, value,
|
|
target, expected_description,
|
|
upstream_error: e,
|
|
})
|
|
}
|
|
}
|
|
|
|
load(value, target=undefined) {
|
|
const coerced_value = this.coerce(value, target);
|
|
this.validate(coerced_value, target);
|
|
return coerced_value;
|
|
}
|
|
|
|
|
|
}
|