Files
zod-schema-class/src/ZodSchemaClass.ts
Julien Valverdé 93f1038e27
Some checks failed
continuous-integration/drone/push Build is failing
ZodSchemaClassOf
2024-02-20 01:08:22 +01:00

75 lines
2.1 KiB
TypeScript

import { expression } from "@thilawyn/traitify-ts"
import { AbstractClass } from "type-fest"
import { z } from "zod"
import { ExtendableZodSchemaObject } from "./traits/ExtendableZodSchemaObject"
import { InstantiableZodSchemaObject } from "./traits/InstantiableZodSchemaObject"
import { Extend, StaticMembers } from "./util"
export function ZodSchemaClassOf<
Super extends AbstractClass<object, []>,
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
Values extends {},
DefaultValues extends Partial<Values>,
>(
of: Super,
{ schema, defaultValues }: {
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>
defaultValues: DefaultValues
},
) {
const exp = expression
.extends(class extends (of as AbstractClass<{}, []>) {
static readonly schema = schema
static readonly defaultValues = defaultValues
constructor(values: Values) {
super()
Object.assign(this, values)
}
})
.expresses(
InstantiableZodSchemaObject,
ExtendableZodSchemaObject,
)
.build()
return exp.extends as AbstractClass<
Extend<[
InstanceType<Super>,
InstanceType<typeof exp.extends>,
Values,
]>,
ConstructorParameters<typeof exp.extends>
> &
Extend<[
StaticMembers<Super>,
StaticMembers<typeof exp.extends>,
]>
}
class DefaultRoot {}
export function ZodSchemaClass<
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
Values extends {},
DefaultValues extends Partial<Values>,
>(
props: {
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>
defaultValues: DefaultValues
},
) {
return ZodSchemaClassOf(DefaultRoot, props)
}