0.1.2 #3

Merged
Thilawyn merged 136 commits from next into master 2024-03-11 19:44:21 +01:00
Showing only changes of commit 1956aae555 - Show all commits

View File

@@ -0,0 +1,73 @@
import { ImplStaticThis, trait } from "@thilawyn/traitify-ts"
import { Class, HasRequiredKeys } from "type-fest"
import { z } from "zod"
import { StaticMembers } from "../util"
type ParseParamsArgs = [] | [params: Partial<z.ParseParams>]
type NewZodSchemaInstanceArgs<Input extends object> = (
HasRequiredKeys<Input> extends true
? [values: Input, ...args: ParseParamsArgs]
: [] | [values: Input, ...args: ParseParamsArgs]
)
export const ZodSchemaObject = <
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
>(
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>,
schemaWithDefaultValues: (
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>
) => z.ZodObject<SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues>,
) => trait
.implement(Super => class ZodSchemaObject extends Super {
static readonly schema = schema
static readonly schemaWithDefaultsValues = schemaWithDefaultValues(schema)
static instantiationSchema<
Instance extends Values
>(
this: (
Class<Instance, [values: Values]> &
StaticMembers<ImplStaticThis<typeof ZodSchemaObject>>
)
) {
return this.schema.transform(values => new this(values))
}
static instantiationSchemaWithDefaultValues<
Instance extends Values
>(
this: (
Class<Instance, [values: Values]> &
StaticMembers<ImplStaticThis<typeof ZodSchemaObject>>
)
) {
return this.schema.transform(values => new this(values))
}
static create<
Instance extends Values
>(
this: (
Class<Instance, [values: Values]> &
StaticMembers<ImplStaticThis<typeof ZodSchemaObject>>
),
...[values, params]: NewZodSchemaInstanceArgs<PartialValues>
) {
return this.instantiationSchema().parse(values, params)
}
})
.build()