0.1.2 #3
73
src/traits/ZodSchemaObject.ts
Normal file
73
src/traits/ZodSchemaObject.ts
Normal 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()
|
||||
Reference in New Issue
Block a user