makeSchemaClass
This commit is contained in:
@@ -0,0 +1 @@
|
||||
export * from "./makeSchemaClass"
|
||||
|
||||
48
src/makeSchemaClass.ts
Normal file
48
src/makeSchemaClass.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Class } from "type-fest"
|
||||
import { z } from "zod"
|
||||
import { StaticMembers, zodObjectRemoveDefaults } from "./util"
|
||||
|
||||
|
||||
export function makeSchemaClass<
|
||||
SchemaWithDefaultValuesT extends z.ZodRawShape,
|
||||
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
|
||||
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
|
||||
SchemaWithDefaultValuesOutput extends SchemaWithDefaultValuesInput, // TODO: apply "StripSchemaInputDefaults"?
|
||||
SchemaWithDefaultValuesInput extends {},
|
||||
>(
|
||||
{
|
||||
schema: schemaWithDefaultValues
|
||||
}: {
|
||||
schema: z.ZodObject<
|
||||
SchemaWithDefaultValuesT,
|
||||
SchemaWithDefaultValuesUnknownKeys,
|
||||
SchemaWithDefaultValuesCatchall,
|
||||
SchemaWithDefaultValuesOutput,
|
||||
SchemaWithDefaultValuesInput
|
||||
>
|
||||
}
|
||||
) {
|
||||
|
||||
const schema = zodObjectRemoveDefaults(schemaWithDefaultValues)
|
||||
|
||||
class SchemaObject {
|
||||
static readonly schema = schema
|
||||
static readonly schemaWithDefaultValues = schemaWithDefaultValues
|
||||
|
||||
readonly schema = schema
|
||||
readonly schemaWithDefaultValues = schemaWithDefaultValues
|
||||
|
||||
constructor(data: z.output<typeof schema>) {
|
||||
Object.assign(this, data)
|
||||
}
|
||||
}
|
||||
|
||||
return SchemaObject as (
|
||||
Class<
|
||||
SchemaObject & z.output<typeof schema>,
|
||||
ConstructorParameters<typeof SchemaObject>
|
||||
> &
|
||||
StaticMembers<typeof SchemaObject>
|
||||
)
|
||||
|
||||
}
|
||||
14
src/tests.ts
Normal file
14
src/tests.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { z } from "zod"
|
||||
import { makeSchemaClass } from "./makeSchemaClass"
|
||||
|
||||
|
||||
const UserSchema = z.object({
|
||||
/** User ID */
|
||||
id: z.bigint().default(-1n)
|
||||
})
|
||||
|
||||
|
||||
const UserSchemaObject = makeSchemaClass({ schema: UserSchema })
|
||||
|
||||
const user = new UserSchemaObject({ id: 1n })
|
||||
user.id
|
||||
@@ -3,6 +3,15 @@ import { mapValues } from "lodash-es"
|
||||
import { z } from "zod"
|
||||
|
||||
|
||||
/**
|
||||
* Represents the static members of a class.
|
||||
* @template C - The class type.
|
||||
*/
|
||||
export type StaticMembers<C> = {
|
||||
[Key in keyof C as Key extends "prototype" ? never : Key]: C[Key]
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Removes default values from a ZodObject schema and returns a new schema.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user