allow bypassing entity data validation for unknown keys in useEntityForm

This commit is contained in:
dswbx
2025-01-16 10:30:28 +01:00
parent 92c3457099
commit 5343d0bd9d
2 changed files with 26 additions and 11 deletions

View File

@@ -193,29 +193,40 @@ export class Entity<
}
// @todo: add tests
isValidData(data: EntityData, context: TActionContext, explain?: boolean): boolean {
isValidData(
data: EntityData,
context: TActionContext,
options?: {
explain?: boolean;
ignoreUnknown?: boolean;
}
): boolean {
if (typeof data !== "object") {
if (explain) {
if (options?.explain) {
throw new Error(`Entity "${this.name}" data must be an object`);
}
}
const fields = this.getFillableFields(context, false);
const field_names = fields.map((f) => f.name);
const given_keys = Object.keys(data);
if (given_keys.some((key) => !field_names.includes(key))) {
if (explain) {
throw new Error(
`Entity "${this.name}" data must only contain known keys, got: "${given_keys}"`
);
if (options?.ignoreUnknown !== true) {
const field_names = fields.map((f) => f.name);
const given_keys = Object.keys(data);
const unknown_keys = given_keys.filter((key) => !field_names.includes(key));
if (unknown_keys.length > 0) {
if (options?.explain) {
throw new Error(
`Entity "${this.name}" data must only contain known keys, unknown: "${unknown_keys}"`
);
}
}
}
for (const field of fields) {
if (!field.isValid(data[field.name], context)) {
console.log("Entity.isValidData:invalid", context, field.name, data[field.name]);
if (explain) {
if (options?.explain) {
throw new Error(`Field "${field.name}" has invalid data: "${data[field.name]}"`);
}