Added coercing system to field configuration, revised some of the data validation errors

This commit is contained in:
2026-04-09 19:17:57 +02:00
parent a088f97e2e
commit 31b6eecdec
3 changed files with 62 additions and 16 deletions

View File

@@ -1,24 +1,43 @@
import { Invalid_Data } from '@efforting.tech/errors';
import { Data_Validation_Failed, Data_Coercion_Failed } from '@efforting.tech/errors';
export class Field_Configuration {
constructor(name, validator=null, expected=undefined) {
Object.assign(this, { name, validator, expected });
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 { validator } = this;
return !validator || validator(value);
const { validation_function } = this;
return !validation_function || validation_function(value);
}
validate(value, target=undefined) {
const { validator, name, expected } = this;
const { validation_function, name, expected_description } = this;
if (!this.check_validation(value)) {
throw new Invalid_Data({
name, validator, value,
target, expected,
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;
}
}