import { Result } from "@webiny/feature/api"; import { WebinyError } from "@webiny/error"; import z from "zod"; type DataProperties = Omit; export type IModelData = { // oxlint-disable-next-line typescript/no-unsafe-function-type [K in keyof DataProperties as T[K] extends Function ? never : K]: T[K]; }; export type IModelInput = IModelData; export abstract class BaseModel = any> { get __schema(): TModel { throw new Error("Schema getter is not implemented!"); } constructor(data: IModelData) { this.validateData(data); this.populate(data); } populate(data: IModelData): void { Object.assign(this, data); } validate(): Result { try { this.validateData(this.toData()); return Result.ok(true); } catch (error) { return Result.fail(error); } } validateOrThrow(): void { this.validateData(this.toData()); } clone(): this { const Constructor = this.constructor as new (data: IModelData) => this; return new Constructor(this.toData()); } toData(): IModelData { if (this.__schema && this.__schema.def?.type === "object") { const result = {} as IModelData; const shape = this.__schema.shape; for (const key in shape) { // always use structuredClone for safety. // @ts-expect-error allow index. result[key] = structuredClone(this[key]); } return result; } return { ...(this as any) } as IModelData; } updateWith(partial: Partial>): void { const updated = { ...this.toData(), ...partial }; this.validateData(updated); this.populate(updated); } protected validateData(data: IModelData): void { const result = this.__schema.safeParse(data); if (!result.success) { throw new WebinyError({ message: "Validation error", code: "DOMAIN_MODEL_VALIDATION_ERROR", data: result.error.issues }); } } }