add validation logs and improve data validation handling (#157)

Added warning logs for invalid data during mutator validation, refined field validation logic to handle undefined values, and adjusted event validation comments for clarity. Minor improvements include exporting events from core and handling optional chaining in entity field validation.
This commit is contained in:
dswbx
2025-04-22 15:44:34 +02:00
committed by GitHub
parent e246396225
commit 5763a6e150
5 changed files with 22 additions and 6 deletions
+4
View File
@@ -14,6 +14,10 @@ export abstract class Event<Params = any, Returning = void> {
params: Params;
returned: boolean = false;
/**
* Shallow validation of the event return
* It'll be deeply validated on the place where it is called
*/
validate(value: Returning): Event<Params, Returning> | void {
throw new EventReturnedWithoutValidation(this as any, value);
}
+1
View File
@@ -27,6 +27,7 @@ export {
export { Registry, type Constructor } from "./registry/Registry";
export * from "./console";
export * from "./events";
// compatibility
export type Middleware = MiddlewareHandler<any, any, any>;
+1 -1
View File
@@ -232,7 +232,7 @@ export class Entity<
}
for (const field of fields) {
if (!field.isValid(data[field.name], context)) {
if (!field.isValid(data?.[field.name], context)) {
$console.warn(
"invalid data given for",
this.name,
+12 -3
View File
@@ -1,4 +1,4 @@
import type { PrimaryFieldType } from "core";
import { $console, type PrimaryFieldType } from "core";
import { Event, InvalidEventReturn } from "core/events";
import type { Entity, EntityData } from "../entities";
import type { RepoQuery } from "../server/data-query-impl";
@@ -9,6 +9,10 @@ export class MutatorInsertBefore extends Event<{ entity: Entity; data: EntityDat
override validate(data: EntityData) {
const { entity } = this.params;
if (!entity.isValidData(data, "create")) {
$console.warn("MutatorInsertBefore.validate: invalid", {
entity: entity.name,
data,
});
throw new InvalidEventReturn("EntityData", "invalid");
}
@@ -36,13 +40,18 @@ export class MutatorUpdateBefore extends Event<
static override slug = "mutator-update-before";
override validate(data: EntityData) {
const { entity, ...rest } = this.params;
const { entity, entityId } = this.params;
if (!entity.isValidData(data, "update")) {
$console.warn("MutatorUpdateBefore.validate: invalid", {
entity: entity.name,
entityId,
data,
});
throw new InvalidEventReturn("EntityData", "invalid");
}
return this.clone({
...rest,
entityId,
entity,
data,
});
+4 -2
View File
@@ -185,12 +185,14 @@ export abstract class Field<
};
}
// @todo: add field level validation
isValid(value: any, context: TActionContext): boolean {
if (value) {
if (typeof value !== "undefined") {
return this.isFillable(context);
} else {
} else if (context === "create") {
return !this.isRequired();
}
return true;
}
/**