ZodSchemaClassExtender
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Julien Valverdé
2024-02-25 04:32:09 +01:00
parent 34ae4b9375
commit e7c65c0a07
3 changed files with 72 additions and 13 deletions

View File

@@ -0,0 +1,59 @@
import { AbstractClass } from "type-fest"
import { z } from "zod"
import { ZodSchemaAbstractClass } from "../shapes/ZodSchemaClass"
import { Extend, StaticMembers } from "../util"
export class ZodSchemaClassExtender<Superclass extends AbstractClass<object>> {
declare ["constructor"]: typeof ZodSchemaClassExtender
constructor(readonly superclass: Superclass) {}
schema<
Super extends ZodSchemaAbstractClass<SuperInstance, SuperSchemaT, SuperSchemaUnknownKeys, SuperSchemaCatchall, SuperValues, SuperDefaultValues>,
SuperInstance extends SuperValues,
SuperSchemaT extends z.ZodRawShape,
SuperSchemaUnknownKeys extends z.UnknownKeysParam,
SuperSchemaCatchall extends z.ZodTypeAny,
SuperValues extends object,
SuperDefaultValues extends Partial<SuperValues>,
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
Values extends SuperValues,
DefaultValues extends Partial<Values>,
>(
this: ZodSchemaClassExtender<
Super | ZodSchemaAbstractClass<SuperInstance, SuperSchemaT, SuperSchemaUnknownKeys, SuperSchemaCatchall, SuperValues, SuperDefaultValues>
>,
props: {
schema: (schema: Super["schema"]) => z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>
defaultValues: (defaultValues: SuperDefaultValues) => DefaultValues
},
) {
const schema = props.schema(this.superclass.schema)
const defaultValues = props.defaultValues(this.superclass.defaultValues)
class Schemas extends (this.superclass as AbstractClass<object, any[]>) {
static readonly schema = schema
static readonly defaultValues = defaultValues
}
return new this.constructor(
this.superclass as unknown as AbstractClass<
Extend<[SuperInstance, Schemas]>,
[values: Values]
> &
Extend<[
StaticMembers<Super>,
StaticMembers<typeof Schemas>,
]>
)
}
}