105 lines
3.3 KiB
TypeScript
105 lines
3.3 KiB
TypeScript
import { trait } from "@thilawyn/traitify-ts"
|
|
import { Effect, pipe } from "effect"
|
|
import { HasRequiredKeys } from "type-fest"
|
|
import { z } from "zod"
|
|
import { ZodSchemaClass } from "../shapes/ZodSchemaClass"
|
|
import { parseZodTypeEffect } from "../util"
|
|
|
|
|
|
type NewZodSchemaInstanceInput<
|
|
Values extends object,
|
|
DefaultValues extends Partial<Values>,
|
|
> = {
|
|
[Key in Exclude<keyof Values, keyof DefaultValues>]: Values[Key]
|
|
} & {
|
|
[Key in keyof DefaultValues]?: Key extends keyof Values
|
|
? Values[Key]
|
|
: never
|
|
}
|
|
|
|
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 InstantiableZodSchemaObject = trait
|
|
.implement(Super => class InstantiableZodSchemaObject extends Super {
|
|
static create<
|
|
Instance extends Values,
|
|
|
|
SchemaT extends z.ZodRawShape,
|
|
SchemaUnknownKeys extends z.UnknownKeysParam,
|
|
SchemaCatchall extends z.ZodTypeAny,
|
|
|
|
Values extends object,
|
|
DefaultValues extends Partial<Values>,
|
|
>(
|
|
this: ZodSchemaClass<Instance, SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, DefaultValues>,
|
|
|
|
...[values, params]: NewZodSchemaInstanceArgs<
|
|
NewZodSchemaInstanceInput<Values, DefaultValues>
|
|
>
|
|
) {
|
|
return new this(
|
|
this.schema.parse({ ...this.defaultValues, ...values }, params)
|
|
)
|
|
}
|
|
|
|
static async createPromise<
|
|
Instance extends Values,
|
|
|
|
SchemaT extends z.ZodRawShape,
|
|
SchemaUnknownKeys extends z.UnknownKeysParam,
|
|
SchemaCatchall extends z.ZodTypeAny,
|
|
|
|
Values extends object,
|
|
DefaultValues extends Partial<Values>,
|
|
>(
|
|
this: ZodSchemaClass<Instance, SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, DefaultValues>,
|
|
|
|
...[values, params]: NewZodSchemaInstanceArgs<
|
|
NewZodSchemaInstanceInput<Values, DefaultValues>
|
|
>
|
|
) {
|
|
return new this(
|
|
await this.schema.parseAsync({ ...this.defaultValues, ...values }, params)
|
|
)
|
|
}
|
|
|
|
static createEffect<
|
|
Instance extends Values,
|
|
|
|
SchemaT extends z.ZodRawShape,
|
|
SchemaUnknownKeys extends z.UnknownKeysParam,
|
|
SchemaCatchall extends z.ZodTypeAny,
|
|
|
|
Values extends object,
|
|
DefaultValues extends Partial<Values>,
|
|
>(
|
|
this: ZodSchemaClass<Instance, SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, DefaultValues>,
|
|
|
|
...[values, params]: NewZodSchemaInstanceArgs<
|
|
NewZodSchemaInstanceInput<Values, DefaultValues>
|
|
>
|
|
) {
|
|
return pipe(
|
|
parseZodTypeEffect(
|
|
this.schema,
|
|
{ ...this.defaultValues, ...values },
|
|
params,
|
|
),
|
|
|
|
Effect.map(values => new this(values)),
|
|
)
|
|
}
|
|
|
|
protected static initialize() {
|
|
|
|
}
|
|
})
|
|
.build()
|