From c3c454eb15d80169913493bad0ab37c46462748a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julien=20Valverd=C3=A9?= Date: Wed, 28 Feb 2024 02:57:30 +0100 Subject: [PATCH] ZodSchemaObject work --- src/traits/ZodSchemaObject.ts | 32 +++++++++++++++++++++++++------- src/util/effect.ts | 9 +++------ 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/src/traits/ZodSchemaObject.ts b/src/traits/ZodSchemaObject.ts index b39d34c..b4f1e29 100644 --- a/src/traits/ZodSchemaObject.ts +++ b/src/traits/ZodSchemaObject.ts @@ -1,7 +1,7 @@ import { ImplStaticThis, trait } from "@thilawyn/traitify-ts" import { Class, HasRequiredKeys } from "type-fest" import { z } from "zod" -import { StaticMembers } from "../util" +import { StaticMembers, parseZodSchemaEffect } from "../util" type ParseParamsArgs = [] | [params: Partial] @@ -50,20 +50,38 @@ export const ZodSchemaObject = < >( this: Class & Self ) { - return this.schema.transform(values => new this(values)) + return this.schemaWithDefaultsValues.transform(values => new this(values)) } static create< - Instance extends Values + Self extends StaticMembers>, + Instance extends Values, >( - this: ( - Class & - StaticMembers> - ), + this: Class & Self, ...[values, params]: NewZodSchemaInstanceArgs ) { return this.instantiationSchemaWithDefaultValues().parse(values, params) } + + static createPromise< + Self extends StaticMembers>, + Instance extends Values, + >( + this: Class & Self, + ...[values, params]: NewZodSchemaInstanceArgs + ) { + return this.instantiationSchemaWithDefaultValues().parseAsync(values, params) + } + + static createEffect< + Self extends StaticMembers>, + Instance extends Values, + >( + this: Class & Self, + ...[values, params]: NewZodSchemaInstanceArgs + ) { + return parseZodSchemaEffect(this.instantiationSchemaWithDefaultValues(), values, params) + } }) .build() diff --git a/src/util/effect.ts b/src/util/effect.ts index f7ce9eb..b4da92b 100644 --- a/src/util/effect.ts +++ b/src/util/effect.ts @@ -3,16 +3,13 @@ import { z } from "zod" /** - * Parses a value using a ZodType schema wrapped in an Effect monad. + * Parses a value using a Zod schema wrapped in an Effect monad. * - * @param schema - The ZodType schema to use for parsing. + * @param schema - The Zod schema to use for parsing. * @param args - The arguments to pass to the `safeParseAsync` method of the schema. * @returns An Effect monad representing the parsing result. */ -export const parseZodTypeEffect = < - Output, - Input, ->( +export const parseZodSchemaEffect = ( schema: z.ZodType, ...args: Parameters ) => pipe(