diff --git a/src/traits/JsonifiedZodSchemaObject.ts b/src/traits/JsonifiedZodSchemaObject.ts index 2e6c93c..ed0da83 100644 --- a/src/traits/JsonifiedZodSchemaObject.ts +++ b/src/traits/JsonifiedZodSchemaObject.ts @@ -1,7 +1,8 @@ -import { TraitClass, expression } from "@thilawyn/traitify-ts" -import { Jsonifiable } from "type-fest" +import { ImplStatic, TraitClass, trait } from "@thilawyn/traitify-ts" +import { Class, Jsonifiable } from "type-fest" import { z } from "zod" -import { ZodSchemaObject, ZodSchemaObjectTrait } from "./ZodSchemaObject" +import { parseZodSchemaEffect } from "../util" +import { ZodSchemaObjectTrait } from "./ZodSchemaObject" export const JsonifiedZodSchemaObject = < @@ -28,13 +29,74 @@ export const JsonifiedZodSchemaObject = < schema: typeof of.schema ) => z.ZodObject, }, -) => expression - .expresses(ZodSchemaObject(of.schemaWithDefaults)) +) => trait + .implement(Super => class JsonifiedZodSchemaObjectImpl extends Super { + static readonly of = of as Of + static readonly jsonifySchema = props.jsonifySchema(of.schema) + static readonly dejsonifySchema = props.dejsonifySchema(of.schema) + + + static pipeSchemaIntoInstance< + Instance extends JsonifiedValues, + + SchemaT extends z.ZodRawShape, + SchemaUnknownKeys extends z.UnknownKeysParam, + SchemaCatchall extends z.ZodTypeAny, + SchemaOutput extends JsonifiedValues, + SchemaInput, + >( + this: Class, + schema: z.ZodObject, + ) { + return schema.transform(values => new this(values)) + } + + + static jsonify< + Instance extends JsonifiedValues + >( + this: ( + Class & + ImplStatic + ), + values: Values, + params?: Partial, + ) { + return this + .pipeSchemaIntoInstance(this.jsonifySchema) + .parse(values, params) + } + + static jsonifyPromise< + Instance extends JsonifiedValues + >( + this: ( + Class & + ImplStatic + ), + values: Values, + params?: Partial, + ) { + return this + .pipeSchemaIntoInstance(this.jsonifySchema) + .parseAsync(values, params) + } + + static jsonifyEffect< + Instance extends JsonifiedValues + >( + this: ( + Class & + ImplStatic + ), + values: Values, + params?: Partial, + ) { + return parseZodSchemaEffect( + this.pipeSchemaIntoInstance(this.jsonifySchema), + values, + params, + ) + } + }) .build() - .subtrait() - .implement(Super => class JsonifiedZodSchemaObjectImpl extends Super { - static readonly of = of as Of - static readonly jsonifySchema = props.jsonifySchema(of.schema) - static readonly dejsonifySchema = props.dejsonifySchema(of.schema) - }) - .build()