diff --git a/bun.lockb b/bun.lockb index 9deffd2..c13519a 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/package.json b/package.json index 6f2f43d..0cc9792 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "clean:node": "rm -rf node_modules" }, "dependencies": { - "@thilawyn/traitify-ts": "^0.1.0", + "@thilawyn/traitify-ts": "^0.1.1", "decimal.js": "^10.4.3", "effect": "^2.2.3", "lodash-es": "^4.17.21", diff --git a/src/ZodSchemaClass.ts b/src/ZodSchemaClass.ts index 3b79414..8dd08e1 100644 --- a/src/ZodSchemaClass.ts +++ b/src/ZodSchemaClass.ts @@ -3,6 +3,57 @@ import { AbstractClass, Class as ConcreteClass, Opaque } from "type-fest" import { z } from "zod" import { DefinedDefaultValuesTag, NewZodSchemaInstanceArgs, NewZodSchemaInstanceInput, TZodSchemaClass } from "." import { Class, ClassesInstances, ClassesStaticMembers, GetClassType, MergeInheritanceTree, MergeInheritanceTreeWithoutOverriding, parseZodTypeEffect } from "./util" +import { abstract, trait } from "@thilawyn/traitify-ts" + + +export const InstantiableZodSchemaObject = < + SchemaT extends z.ZodRawShape, + SchemaUnknownKeys extends z.UnknownKeysParam, + SchemaCatchall extends z.ZodTypeAny, + + Values extends {}, + DefaultValues extends Partial, +>() => trait( + abstract(), + + Super => class InstantiableZodSchemaObject extends Super { + static create( + ...[values, params]: NewZodSchemaInstanceArgs< + NewZodSchemaInstanceInput + > + ) { + return new this( + this.schema.parse({ ...this.defaultValues, ...values }, params) + ) + } + + static async createPromise( + ...[values, params]: NewZodSchemaInstanceArgs< + NewZodSchemaInstanceInput + > + ) { + return new this( + await this.schema.parseAsync({ ...this.defaultValues, ...values }, params) + ) + } + + static createEffect( + ...[values, params]: NewZodSchemaInstanceArgs< + NewZodSchemaInstanceInput + > + ) { + return pipe( + parseZodTypeEffect( + this.schema, + { ...this.defaultValues, ...values }, + params, + ), + + Effect.map(values => new this(values)), + ) + } + }, +) export function ZodSchemaClassOf<