Added basic schema to field-configuration

This commit is contained in:
2026-04-09 19:55:38 +02:00
parent 31b6eecdec
commit 0cdc4e271b
3 changed files with 93 additions and 19 deletions

View File

@@ -1,8 +1,8 @@
import { Data_Validation_Failed, Data_Coercion_Failed } from '@efforting.tech/errors';
import { Data_Validation_Failed, Data_Coercion_Failed, Superfluous_Data_Field } 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 });
constructor(validation_function=null, coercion_function=null, factory_function=null, expected_description=undefined) {
Object.assign(this, { validation_function, coercion_function, factory_function, expected_description });
}
check_validation(value) {
@@ -11,29 +11,36 @@ export class Field_Configuration {
}
validate(value, target=undefined) {
const { validation_function, name, expected_description } = this;
const { validation_function, expected_description } = this;
if (!this.check_validation(value)) {
throw new Data_Validation_Failed({
name, validation_function, value,
validation_function, value,
target, expected_description,
});
}
}
coerce(value, target=undefined) {
const { coercion_function, name, expected_description } = this;
const { coercion_function, expected_description } = this;
try {
return coercion_function ? coercion_function(value) : value;
} catch (e) {
throw new Data_Coercion_Failed({
name, coercion_function, value,
coercion_function, value,
target, expected_description,
upstream_error: e,
})
}
}
load(value, target=undefined) {
load(value=undefined, target=undefined) {
const { factory_function } = this;
if ((value === undefined) && factory_function) {
value = factory_function(target);
}
const coerced_value = this.coerce(value, target);
this.validate(coerced_value, target);
return coerced_value;
@@ -41,3 +48,32 @@ export class Field_Configuration {
}
export class Schema {
constructor(field_schema) {
Object.assign(this, { field_schema });
}
load(value={}, target=undefined) {
const { field_schema } = this;
for (const [value_name, value_value] of Object.entries(value)) {
if (!field_schema[value_name]) {
throw new Superfluous_Data_Field({
field_value: value_value, field_name: value_name, target,
});
}
}
const result = {};
for (const [field_name, field_config] of Object.entries(field_schema)) {
const sub_target = { schema: this, field_name, field_config, parent_target: target };
result[field_name] = field_config.load(value[field_name], sub_target);
}
return result;
}
}